首页 > 解决方案 > 使用 POST API 时出现多个 CORS 错误

问题描述

尝试通过 POST 请求上传图像时出现多个 CORS 错误。我在 AWS API Gateway 上创建了一个 POST API,它触发了一个用 Node js 编写的 lambda 函数。该 API 与 Postman 一起工作得很好,因为它允许 CORS,但它在不同的浏览器上给出了多个错误。

错误如下:-

在此处输入图像描述

以下是请求标头:-

Method request headers: {
        sec - fetch - mode = cors,
        sec - fetch - site = cross - site,
        accept - language = en - US,
        en;q = 0.9,
        hi;q = 0.8,
        access - control - allow - headers = Origin,
        X - Requested - With,
        Content - Type,
        Accept,
        Authorization,
        origin = null,
        User - Agent = Mozilla / 5.0(Windows NT 10.0; Win64; x64) AppleWebKit / 537.36(KHTML, like Gecko) Chrome / 76.0 .3809 .100 Safari / 537.36,
        X - Forwarded - Proto = https,
        Host = xxxxxxx.execute - api.us - east - 2. amazonaws.com,
        X - Forwarded - Port = 443,
        X - Amzn - Trace - Id = Root = 1 - 5 d5fd816 - 4 c1ac880ed09a50047ecda00,
        accept = * /*, access-control-allow-origin=*, X-Forwarded-For=103.97.240.210, content-type=application/json, accept-encoding=gzip, deflate, br}

Chrome 上的请求标头 在此处输入图像描述

以下是**响应标题:-**

Endpoint response headers: {
    Date = Fri,
    23 Aug 2019 12: 12: 07 GMT,
    Content - Type = application / json,
    Content - Length = 1077,
    Connection = keep - alive,
    x - amzn - RequestId = 46 a264c2 - 44 d7 - 4026 - 9168 - f227e758f078,
    X - Amz - Function - Error = Unhandled,
    x - amzn - Remapped - Content - Length = 0,
    X - Amz - Executed - Version = $LATEST,
    X - Amzn - Trace - Id = root = 1 - 5 d5fd816 - 4 c1ac880ed09a50047ecda00;sampled = 0
}

邮递员上的响应标头 在此处输入图像描述

下面是我的代码 客户端:index.html

<body>

<form method="post" enctype="application/json">

    Enter the Employee Id: <input type="text" name="empId"><br>
    Upload the Employee Photo: </h2><input type="file" name="PhotoName"> <br>
    <input type="submit" name="PhotoContent" value="Upload Photo"><br><br>
</form>
</div>

 <script src="upload.js"></script>

</body>

客户端:upload.js

const url = 'https://xxxxxxx.execute-api.us-east-2.amazonaws.com/test/upload';
const form = document.querySelector('form');

form.addEventListener('submit', e => {
    e.preventDefault();

    const files = document.querySelector('[type=file]').files;


    const reader = new FileReader() 
    reader.onload = handleFileLoad;
    reader.readAsBinaryString(files[0]);
    for (let i = 0; i < files.length; i++) {
        let file = files[i];
        console.log(file);

    }

});

function handleFileLoad(event){ 
    console.log(event);
    let formData = new FormData();
    formData.append('data', event.target.result);
    console.log('final file ', formData.get('data'));

    let data = {
        "fileName" : 'tmp123',
        "user_avatar" : event.target.result
    };

    fetch(url, {
        method: 'POST',
        body: JSON.stringify(data),
        headers : {
            'Origin' : 'https://xxxxxxx.execute-api.us-east-2.amazonaws.com/test/upload',
            'content-type' : 'application/json',
            'Access-Control-Allow-Origin' : '*',
            'Access-Control-Allow-Headers' : 'Origin, X-Requested-With, Content-Type, Accept, Authorization',
        },
    }).then(response => {
        console.log(response);
    });
}

服务器端(lambda):index.js

const AWS = require('aws-sdk');
const { parse } = require('querystring');
var s3 = new AWS.S3();
exports.handler = (event, context, callback) => {   
    if (event.method === 'POST') {
    let body = '';
    event.on('data', chunk => {
        body += chunk.toString();
    });
    req.on('end', () => {
        console.log(
            parse(body)
        );
        res.end('ok');
    });
}
    //  var event = '{ "user_avatar": "asas" }' ;

    let encodedImage = JSON.parse(event.body).user_avatar;
    let decodedImage = Buffer.from(encodedImage, 'base64');
    //  var filePath = "avatars/" + event.queryStringParameters.username + ".jpg"
     var filePath = JSON.parse(event.body).file_name

     var params = {
       "Body": decodedImage,
       "Bucket": "test-bkt-rahul",
       "Key": filePath  
    };
    s3.upload(params, function(err, data){
       if(err) {
           callback(err, null);
       } else {
           let response = {
        "statusCode": 200,
        "headers": {
            "Access-Control-Allow-Origin": ""
        },
        "body": JSON.stringify(data),
        "isBase64Encoded": false
    };
           callback(null, response);
    }
    });

};

任何建议将不胜感激。提前致谢。

标签: node.jspostaws-lambdacorsaws-api-gateway

解决方案


最后,问题解决了。

  • 我收到了 403 响应代码,因为我使用了不正确的端点。
  • 我收到 CORS 错误,因为我的服务器端代码没有进行异常处理。在异常情况下,代码未在响应中发送 CORS 标头。

推荐阅读