【问题标题】:Angular $http.post and No 'Access-Control-Allow-Origin' headerAngular $http.post 并且没有“Access-Control-Allow-Origin”标头
【发布时间】:2014-06-22 13:51:34
【问题描述】:

我有两个带有 nodejs 的应用程序和 angularjs.nodejs 应用程序有一些这样的代码:

require('http').createServer(function(req, res) {


  req.setEncoding('utf8');
  var body = '';
  var result = '';
  req.on('data', function(data) {
      // console.log("ONDATA");

      //var _data = parseInput( data,req.url.toString());
      var _data = parseInputForClient(data, req.url.toString());



      switch (req.url.toString()) {
          case "/cubes":
              {

这个应用程序主机在http://localhost:4000.angularjs 应用程序主机与节点http-server 模块在localhost://www.localhost:3030.in 我的angularjs 服务之一我有这样的事情:

fetch:function(){
         var data = '{somedata:"somedata"}';
        return $http.post('http://localhost:4000/cubes',data).success(function(cubes){
            console.log(cubes);
        });
    }

但是当这个服务向服务器发送请求时得到这个错误:

XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access. 

所以我在网上和 stackoverflow 上搜索了一些主题,然后我找到了 thisthis 。根据这些主题,我将服务器中的响应标头更改为以下内容:

res.writeHead(200, {
                          'Content-Type': 'application/json',
                          "Access-Control-Allow-Origin": "*"
                      });
                      res.end(JSON.stringify(result));

但是这不起作用。我尝试使用 firefox、chrome 并使用 Telerik Fiddler Web Debugger 检查请求,但服务器仍处于挂起状态,我收到 Access Control Allow Origin 错误。

【问题讨论】:

标签: javascript node.js angularjs angularjs-service


【解决方案1】:

你做POST请求,根据CORS规范生成预检请求:http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

您的服务器也应该响应 OPTIONS 方法(除了 POST),并在那里返回 Access-Control-Allow-Origin

您可以看到这是原因,因为当您的代码在“网络”选项卡(或 Fiddler 代理调试器)中创建请求时,您应该会看到带有 ORIGIN 标头的 OPTIONS 请求

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2016-01-21
    • 1970-01-01
    • 2014-12-15
    • 2014-01-20
    • 2017-09-19
    • 2015-04-02
    相关资源
    最近更新 更多