当 rest api 应用程序服务器(express)和 Angulars js 应用程序在不同的端口上运行时,Cors

Cors issue when rest api application server(express) and Angulars js application running on different port

本文关键字:应用程序 Cors 运行时 js 服务器 api rest express Angulars      更新时间:2023-09-26

我有用node编写的rest api应用程序.js和express在同一服务器上的端口3000上运行,angularjs应用程序在同一服务器上的端口9001上运行。在从 angularjs 应用程序调用 rst api 时,它给出了 cors 问题。

在 rest api 应用程序中,我使用了"cors"模块

var cors = require('cors');
app.use(cors());

但它给了我以下错误

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3000/api/user/login. This can be fixed by moving the resource to the same domain or enabling CORS

请求头和响应头如下

响应标头

Content-Length 222
Content-Type application/json; charset=utf-8
Date Tue, 16 Dec 2014 08:40:05 GMT
X-Powered-By Express

查看源代码

请求标头

Accept application/json, text/plain, /
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Authorization null
Content-Length 47
Content-Type application/json;charset=utf-8
Host localhost:3000
Origin http://localhost:9001
Referer http://localhost:9001/
User-Agent Mozilla/5.0 (Windows NT 6.2; WOW64; rv:35.0) Gecko/20100101 Firefox/35.0

谢谢

我通过添加行 app.options('*', cors((( 来解决它;就在所有路由之前。

这是一个带有http-request-header"OPTIONS"的预检请求问题

您可以将解决方案设置为

app.configure('development', function(){
    app.set('origins', '*:*');
}