'TypeError: headers[key].trim is not a function
I'm trying to execute an API on AWS, that requires a CORS headers, i make the request with all the information but i receive the next error:
"TypeError: headers[key].trim is not a function"
If i not send de CORS, i receive the error:
from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My code:
async function Request(){
let arra = "test"
const data2 = {
"parm1" : "one", "parm2" : "two"
};
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Credentials": true
};
try{
const resp = await API.post("Lambda", "/admin/digital/app/uploadtodynamo", {
body: data2, headers: headers
});
console.log("error 1")
console.log(resp)
}
catch(error)
{
console.log("error 2")
console.log(error)
}
}
React version: "^16.12.0"
Amplify: "^2.2.5"
Solution 1:[1]
I encountered this error due to providing incorrect Tagging-value to my PutObjectCommand.
It should be a key-value formatted string, i.e. "key=value;key=value". However, I accidentally supplied a boolean, false:
async function uploadFile(fileContent, fileKey, contentType, tagging) {
try {
await s3.send(
new PutObjectCommand({
Bucket: UploadBucketName,
Key: fileKey,
Body: fileContent,
Tagging: tagging, // <-- ERROR
}),
);
const getCommand = new GetObjectCommand({
Bucket: UploadBucketName,
ContentType: contentType,
ACL: 'public-read',
Key: fileKey,
});
return getSignedUrl(s3, getCommand, { expiresIn: 3600 });
} catch (e) {
throw new Error(`Could not upload file to S3 ${e}`);
}
}
Protip: Use TypeScript.
Solution 2:[2]
Chiming in, I got this error when using Metadata. One of my fields was a number.
const uploaded = await sendUploadCommand(new PutObjectCommand({
ACL: "authenticated-read",
Bucket: myBucket,
Body: file,
Key: `/${folder}/${filename}.${r.ext}`,
ContentType: r.mime,
Metadata: {
userId: user.id, // A string, this is fine
flags: user.flags // ? A number, this is the error! Add '.toString()'
}
}));
The documentation states that Metadata should be KV of strings:
PutObjectRequest.Metadata?: {[p: string]: string}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | maxpaj |
| Solution 2 | ifh |
