【问题标题】:No 'Access-Control-Allow-Origin' header is present on the requested resource (express + react/redux) [duplicate]请求的资源上没有“Access-Control-Allow-Origin”标头(express + react/redux)[重复]
【发布时间】:2019-01-13 18:23:34
【问题描述】:

我的 React 应用程序出现此错误。 “无法加载 https://app-name.herokuapp.com/users/:请求的资源上不存在‘Access-Control-Allow-Origin’标头。因此,不允许访问源‘http://localhost:3000’。”

我的 Express 应用中的代码

 var express = require('express');
 var router = express.Router();

 router.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, X-Auth-Token, Accept");
      next();
  }

我的 Redux 提取调用中的代码

 return dispatch => {
    const url = "https://app-name.herokuapp.com/users/";
    return fetch(url, {
      method: 'GET',
      mode: 'cors',
    })
    .then(handleErrors)
    .then(res => res.json())....

【问题讨论】:

    标签: express heroku redux cors fetch


    【解决方案1】:

    这是您的 WebService 的问题,当您从一个域指向另一个域时会发生这种情况,就像我从 localhost:3000 指向 localhost:3001 一样,这些是不同的,您应该在 WebService 中启用 CORS 以允许该请求。

    您必须寻找一种在 Heroku 应用中启用 CORS 的方法,据我所知,外部 API 调用在免费域中被阻止,但 Heroku 不知道。

    【讨论】:

    • 那么我的heroku中的端口也应该指向3001吗?因为这就是我的反应应用中发生的事情
    • 你应该在你的 Heroku 应用中允许 CORS。也许它可以帮助:stackoverflow.com/questions/11001817/…
    【解决方案2】:

    我想通了。我所要做的就是推送到我的 heroku 应用程序。我不知道它有自己的 git repo。掌心。

    【讨论】:

      猜你喜欢
      • 2021-02-23
      • 2021-09-25
      • 2015-06-15
      • 2017-02-07
      • 2023-03-16
      • 2014-07-30
      • 2016-01-14
      • 2023-03-15
      • 2018-12-02
      相关资源
      最近更新 更多