向本地主机请求远程服务器获取预检请求'Access-Control-Allow-Origin'

完整的错误是这样的:

XMLHttpRequest无法加载http:// ip:port / path 。 对预检请求的响应不会通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。 原因' http:// localhost:3000 '因此不被允许访问。

环境细节:

用尽几乎所有的东西,但不能完成任务。

其实我从angular js客户端请求node.js服务器。 我已经尝试了所有可能的select。

stream程就是这样的:

  1. 请求从在angularjsdevise的门户网站发起。
  2. 在远程机器上点击node.js服务器。

我曾经试过的

expressjs / cors和本地主机NodeJS + Express解决“访问控制允许来源”

客户端代码


$scope.testFunc = function () { $("div#preloader").show(); $http.post(rtcControlUrl, data).success(function () { $("div#preloader").hide(); if(response.success) $.notify(response.msg, "success"); else $.notify(response.msg); console.log(response.data); }).error(function () { $.notify("Request timeout!"); $("div#preloader").hide(); }); }; app.post("/path", cors(), function(req, res) { shelljs.exec("bash test.sh",{silent:true,async:false}).output; console.log(output); res.json({"success": true, msg: 'some text', 'data' : output}); } }); 

错误消息说明对预检请求的响应

如果您查看预检请求,您会看到使用OPTIONS方法。

“预检”请求首先通过OPTIONS方法向另一个域上的资源发送HTTP请求

你的代码:

app.post(“/ path”,cors()

…仅在POST请求中使用Cors中间件。

您也需要处理OPTIONS请求。

我通过使用带请求标头的NPM请求模块来解决此问题

 { name : 'content-type', value: 'application/x-www-form-urlencoded' } 

现在我解决了这个问题,没有在服务器端代码上设置任何头。 我分三步实现了这一点。

客户

 $scope.testFunction= function () { $("div#preloader").show(); $http.get(url).success(function (response) { $("div#preloader").hide(); if(response.success) $.notify(response.msg, "success"); else $.notify(response.msg); console.log(response.data); }).error(function () { $.notify("Request timeout!"); $("div#preloader").hide(); }); }; 

本地节点服务器

 request({ url : url, method : "POST", json : true, headers: [ { name : 'content-type', value: 'application/x-www-form-urlencoded' } ], body : data }, function optionalCallback(err, response) { if (err) { console.error('**************[page][functionName][Request][Fail]*****************', err); res.json({success: false, msg: 'msg', data: err}); } else { var dataObj = (response && response.body) ? response.body.data : undefined; console.info('*************************[pageName][functionName][Request][Success]**********************'); res.json({success: true, msg: 'msg', data: ''}); } }); 

请按照 本video中 所述的方式记住本地节点服务器标题

terminal服务器,我正在执行最终的业务逻辑。

 var cors = require('cors'); app.options('*', cors()); app.post("/path", cors(), function(req, res) { shelljs.exec("bash test.sh",{silent:true,async:false}).output; console.log(output); res.json({"success": true, msg: 'some text', 'data' : output}); } });