【问题标题】:Angularjs post request error No 'Access-Control-Allow-Origin'Angularjs发布请求错误没有'Access-Control-Allow-Origin'
【发布时间】:2014-10-12 17:38:00
【问题描述】:

我有 index.html 向localhost:3000/SetUser 发送发布请求,但我总是收到错误XMLHttpRequest cannot load https://localhost:3000/SetUser. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost' is therefore not allowed access.

这是我的 Angular 控制器中的代码

$http.post("https://localhost:3000/SetUser", {'a':'b'}).success(function(data, status, headers, config) {
 console.log('data', data);
});

这是我的 server.js(nodejs) app.post 上的代码

app.post('/SetUser', function(req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE'); 
    res.end();
    console.log("New user added ", req.body);
});

我什么都试过了,不知道有什么办法可以解决这个问题。 谢谢!

【问题讨论】:

  • 那个特定的路由在运行在 3000 端口的服务器上,对吧?
  • 我发现有时使用* 并不总是按预期工作,具体取决于所使用的后端,您是否尝试使用应用程序的地址代替?
  • @gillesc 如果是这种情况,您会收到特定的错误消息。 wildcards (*) not accepted.. 之类的东西(现在我脑子里没有确切的短语)。我的猜测是,您的 server.js 功能永远不会运行,并且您的标头根本没有设置为允许 cors。

标签: javascript node.js angularjs express


【解决方案1】:

确保一切都在同一个端口上运行,它应该可以解决问题, 是的,通过他的错误,可以理解他从端口 80 向端口 3000 发送请求。 是什么阻止您在同一个端口上解析您的应用程序?

你应该更好地解释自己。

【讨论】:

    【解决方案2】:

    深入了解网络选项卡,浏览器发送“预检”请求,这是一个 OPTIONS 请求:https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests

    所以你必须为这个动词设置你的 CORS 标题!

    我建议全局设置:

    app.use(function(req, res, next) {
        res.header('Access-Control-Allow-Origin', 'example.com');
        res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
        res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
        next();
    });
    

    另外注意你的允许标题并完成它们

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-12-06
      • 2017-08-23
      • 2015-11-27
      • 2016-11-04
      • 2018-03-28
      相关资源
      最近更新 更多