【问题标题】:Axios and Vue won't make an api call to my server , due to a cors policy issue由于 cors 政策问题,Axios 和 Vue 不会对我的服务器进行 api 调用
【发布时间】:2019-05-28 08:06:39
【问题描述】:

我在我的 express(Node) 服务器中设置了我的 cors,如下所示:

server.options('*',cors());
server.use(cors());

然后像这样在我的 Vue 网站上拨打电话

axios.default
          .post(url, {
            firstName: this.firstName,
            lastName: this.lastName,
            email: this.email,
            interests: this.interests,
            targetURL: "https://www.joinvurchase.com/email-verified/",
            poolID
          })

但我收到以下错误:

has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

我认为我服务器上的 cors 设置正确,因为当我使用邮递员拨打电话时,它可以正常工作并返回 Access-Control-Allow-Origin →* 标头。此外,当我在我的网站上拨打电话时,它几乎会立即出错。所以它甚至可能无法进入我的服务器。在本地测试时,完全相同的设置有效。将服务器和网站都部署到 Heroku 后,问题就出现了。

【问题讨论】:

    标签: express vue.js cors axios


    【解决方案1】:

    我想通了。我使用谷歌域名,并且我有一个从“mydomain.com”到“www.mydomain.com”的域重新路由。假设这可行,我将我的网址用作 mydomain.com。由于这些呼叫最终被重新路由,因此我的呼叫以 Redirect is not allowed for a preflight request. 失败。所以我只是开始在我的网址中添加 www,问题就消失了。

    【讨论】:

      【解决方案2】:

      你能试试这个吗,这解决了我的cors问题

      app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header("Access-Control-Allow-Methods", "HEAD, OPTIONS, GET, POST, PUT, DELETE");
        res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
        next();
      });
      

      【讨论】:

        猜你喜欢
        • 2021-06-24
        • 2020-12-23
        • 2021-02-26
        • 2020-03-30
        • 2019-09-16
        • 2020-01-15
        • 1970-01-01
        • 2022-11-24
        • 2021-12-07
        相关资源
        最近更新 更多