Cors 错误 AWS Amplify 无服务器函数 Rest API 网关

Cors Errors AWS Amplify Serverless Function Rest API Gateway

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

我收到以下代码的上述错误。

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.

添加另一条路径之前,代码可以正常工作

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

预检请求是一个 OPTIONS 请求,因此请检查您在 API 网关中是否有针对您请求的路径的 OPTIONS 方法,并检查其配置,例如您是否' 通过 OPTIONS 请求发送或期望凭据。根据 Mozilla CORS Documentation.

,不允许在预检请求中包含凭据

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