在2个端口上使用node rest api和angularJS应用程序的CORS问题

我有我的angularJS应用程序(在本地主机:9000)的古典CORS问题试图赶上我的节点服务器(在本地主机:9001)

这里我的restapi(app.js)代码:

var cors = require('cors'); app.use(cors()); app.options('*', cors()); app.all('/*', function(req, res, next) { // CORS headers res.header("Access-Control-Allow-Origin", "*"); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type"); if (req.method == 'OPTIONS') { res.status(200); res.write("Allow: GET,PUT,POST,DELETE,OPTIONS"); res.end(); } else { next(); } }); 

正如你所看到的,我尝试过这些解决scheme是徒劳的:

  • Node.js和AngularJS中的CORS

  • 当restAPI应用程序服务器(express)和Angulars js应用程序运行在不同的端口时,Cors问题

这里是webapp中简单的$ http调用:

 var req = { method: 'GET', url: 'localhost:9001/memories' }; $http(req). success(function(data, status, headers, config) { // this callback will be called asynchronously // when the response is available reutrnStatus.success = true; reutrnStatus.msg = status; memories = data; }). error(function(data, status, headers, config) { // called asynchronously if an error occurs // or server returns response with an error status. reutrnStatus.success = false; reutrnStatus.msg = status; }); 

我也在webapp中尝试了一些解决scheme(在app.js中):

 // Enable AngularJS to send its requests with the appropriate CORS headers // globally for the whole app: .config(['$httpProvider', function ($httpProvider) { $httpProvider.defaults.useXDomain = true; /** * Just setting useXDomain to true is not enough. AJAX request are also * send with the X-Requested-With header, which indicate them as being * AJAX. Removing the header is necessary, so the server is not * rejecting the incoming request. **/ delete $httpProvider.defaults.headers.common['X-Requested-With']; }]); 

但是我快要放弃了,因为它仍然不能正常工作……这给了我同样的错误:

 XMLHttpRequest cannot load localhost:9001/memories. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource. 

而要完全清楚,我遵循该教程的其余api:

  • https://blog.jixee.me/how-to-write-an-api-in-one-week-part-2/

您正在向未知协议提出请求。

Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.

你需要改变这个:

 method: 'GET', url: 'localhost:9001/memories' }; 

对此:

 method: 'GET', url: 'http://localhost:9001/memories' }; 

或者,您可以将其设置为//localhost:9001/memories并且浏览器将使用当前的协议,如果您通过httphttps提供资源,则该协议非常有用。

虽然不相关,你的callback在variables名称中有拼写错误。