TypeError: headers[key].trim is not a function

Viewed 1076

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"

3 Answers

Header Values have to be strings. At some point during sending your request, you (or some library) are trimming the header values from trailing and leading whitespaces. But as the value of the Access-Control-Allow-Credentials header is a boolean and not a string this doesn't work.

Change

"Access-Control-Allow-Credentials": true 

to

"Access-Control-Allow-Credentials": "true"

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.

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}

Related