首页 > 解决方案 > Vercel (Zeit) 托管服务 - 为 REST 请求阻止 CORS

问题描述

情况

我使用 Vercel 托管我的 JSON 数据库,该数据库位于 db.json 中。我有一个站点,我想在其中创建和删除数据库中的对象。我已经配置了 Axios,以便它可以允许 PUT、PATCH、DELETE 请求。

const streams = axios.create({
    // .. where we make our configurations
    baseURL: "https://music-json-server.now.sh/db.json",
    headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Request-Method": "*",
        "Access-Control-Allow-Credentials": "true",
        "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT",
        "Access-Control-Allow-Headers":
            "Origin, X-Requested-With, Content-Type, Accept, Authorization",
        "Content-Type": "application/json",
    },
});

问题 我在启动应用程序时遇到了与 CORS/axios 配置相关的错误。

xhr.js:126 Refused to set unsafe header "Access-Control-Request-Method"

Access to XMLHttpRequest at 'https://music-json-server.now.sh/db.json/' from origin 'http://localhost:3001' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

CORS 阻止应用程序启动。

我试图解决这个问题:

  1. 我联系了支持。这对他们来说不是问题,因为看起来他们支持 CORS。 在此处输入图像描述

  2. 阅读相关文章Zeit (Vercel) Now 无服务器身份验证请求因 CORS 而失败 。建议添加now.json。我认为它不适用于我的情况,因为它使用了 Vercel 的无服务器功能。

标签: javascriptjsoncorsvercel

解决方案


哦,有一个你必须安装和使用的包:https ://expressjs.com/en/resources/middleware/cors.html 遵循本指南,你会很高兴。


推荐阅读