【问题标题】:TypeError: headers[key].trim is not a functionTypeError: headers[key].trim 不是函数
【发布时间】:2021-01-03 11:03:45
【问题描述】:

我正在尝试在 AWS 上执行一个需要 CORS 标头的 API,我使用所有信息发出请求,但收到下一个错误:

“TypeError: headers[key].trim 不是函数”

如果我不发送 de CORS,我会收到错误:

来自原点“http://localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我的代码:

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)
    }
}

反应版本:“^16.12.0”

放大:“^2.2.5”

【问题讨论】:

  • 对不起,我想念“标题:标题”。 API 是 AWS Amplify 的形式,这是一个与 AWS 一起工作的框架。从“aws-amplify”导入 { API }

标签: javascript node.js reactjs amazon-web-services aws-api-gateway


【解决方案1】:

标题值必须是字符串。在发送请求期间的某个时刻,您(或某些库)正在从尾随和前导空格中修剪标头值。但是由于 Access-Control-Allow-Credentials 标头的值是布尔值而不是字符串,因此这是行不通的。

改变

"Access-Control-Allow-Credentials": true 

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

【讨论】:

  • 我收到此消息:来自原点“localhost:3000”已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。
  • 您的服务器在回答时没有添加所需的 cors 标头。
  • 顺便说一句,无需将 CORS 标头从客户端发送到服务器。但是服务器必须在其对客户端的响应中包含 CORS 标头。
  • 你是正确的 derpirscher,我在 lambda 的答案中添加了 CORS,并立即工作。 (PD:我不知道如何标记为解决方案)
  • @MateoBuitrago 只需点击答案旁边的复选标记
【解决方案2】:

由于向我的PutObjectCommand 提供了不正确的Tagging-value,我遇到了这个错误。

它应该是一个键值格式的字符串,即"key=value;key=value"。但是,我不小心提供了一个布尔值,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:使用 TypeScript。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 2019-09-23
    • 2020-06-29
    • 2020-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-03-03
    相关资源
    最近更新 更多