【问题标题】:Cors Errors AWS Amplify Serverless Function Rest API GatewayCors 错误 AWS Amplify 无服务器函数 Rest API 网关
【发布时间】:2022-01-28 18:12:40
【问题描述】:

CORS 已阻止从源“http://localhost:3000”访问“https://***.execute-api.us-east-1.amazonaws.com/dev/users”处的 XMLHttpRequest策略:对预检请求的响应未通过访问控制检查:它没有 HTTP ok 状态。

以下代码出现上述错误。

const user = await Auth.currentAuthenticatedUser();
    const token = user.signInUserSession.idToken.jwtToken;
    const header = {
        headers: {
            Authorization: token,
        },
    };
    const resp = await API.get("OneRestApi", "/users", header);

    

但是从邮递员调用端点 https://***.execute-api.us-east-1.amazonaws.com/dev/users 不会导致错误。邮递员输出:

{
"success": "get call succeed!",
"url": "/users"

}

但是当我切换到另一个端点“/campaigns”时

   const user = await Auth.currentAuthenticatedUser();
    const token = user.signInUserSession.idToken.jwtToken;
    const header = {
        headers: {
            Authorization: token,
        },
    };
    const resp = await API.get("OneRestApi", "/campaigns", header);

代码运行成功。从 APIGateWay 我启用了 cors。这是“/users”路径的 lambda 代码。

/*
Copyright 2017 - 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. A copy of the License is located at
    http://aws.amazon.com/apache2.0/
or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
*/

var express = require("express");
var bodyParser = require("body-parser");
var awsServerlessExpressMiddleware = require("aws-serverless-express/middleware");

// declare a new express app
var app = express();
app.use(bodyParser.json());
app.use(awsServerlessExpressMiddleware.eventContext());

// Enable CORS for all methods
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "*");
    next();
});

/**********************
 * Example get method *
 **********************/

app.get("/users", function (req, res) {
    // Add your code here
    res.json({ success: "get call succeed!", url: req.url });
});

app.get("/users/*", function (req, res) {
    // Add your code here
    res.json({ success: "get call succeed!", url: req.url });
});

/****************************
 * Example post method *
 ****************************/

app.post("/users", function (req, res) {
    // Add your code here
    res.json({ success: "post call succeed!", url: req.url, body: req.body });
});

app.post("/users/*", function (req, res) {
    // Add your code here
    res.json({ success: "post call succeed!", url: req.url, body: req.body });
});

/****************************
 * Example put method *
 ****************************/

app.put("/users", function (req, res) {
    // Add your code here
    res.json({ success: "put call succeed!", url: req.url, body: req.body });
});

app.put("/users/*", function (req, res) {
    // Add your code here
    res.json({ success: "put call succeed!", url: req.url, body: req.body });
});

/****************************
 * Example delete method *
 ****************************/

app.delete("/users", function (req, res) {
    // Add your code here
    res.json({ success: "delete call succeed!", url: req.url });
});

app.delete("/users/*", function (req, res) {
    // Add your code here
    res.json({ success: "delete call succeed!", url: req.url });
});

app.listen(3000, function () {
    console.log("App started");
});

// Export the app object. When executing the application local this does nothing. However,
// to port it to AWS Lambda we will create a wrapper around that will load the app from
// this file
module.exports = app;

有趣的是,在我向 API 添加另一个路径之前,代码就可以工作了。

【问题讨论】:

    标签: aws-lambda aws-api-gateway aws-amplify aws-sdk-nodejs


    【解决方案1】:

    您的preflight request 有问题。预检请求仅由浏览器发送,而不是由 Postman 等工具发送,这就是 Postman 请求仍然有效的原因。

    预检请求是一个OPTIONS 请求,因此请检查您在 API Gateway 中是否有针对您请求的路径的 OPTIONS 方法,并检查其配置,例如您没有发送或期望使用选项请求。根据Mozilla CORS Documentation,不允许在预检请求中包含凭据。

    添加另一个路径后请求停止工作的原因可能是您在 API Gateway 控制台中对 API 进行了手动更改(可能与身份验证或 CORS 有关)。然后,当您使用 Amplify 推送相同的 API 时,这些更改通常会被过度使用。请检查情况是否如此。并尝试通过 Amplify API 进行所有更改(如果您在那里创建了 API)以避免这些问题。

    【讨论】:

    • 问题已解决。通过 amplify-cli 推送 API 后,我曾经从 APIGateway 控制台启用 CORS 并重新部署 API。这可能是出现错误的原因。上次我没有从控制台启用 cors。效果很好。
    猜你喜欢
    • 2020-07-10
    • 2018-03-19
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 2021-01-18
    • 1970-01-01
    • 2021-01-29
    • 2018-08-27
    相关资源
    最近更新 更多