【问题标题】:Cors issue when rest api application server(express) and Angulars js application running on different port当rest api应用程序服务器(express)和Angulars js应用程序在不同端口上运行时出现Cors问题
【发布时间】:2015-02-14 11:35:55
【问题描述】:

我有用 node.js & express 编写的 rest api 应用程序在端口 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.use(cors());

标签: javascript angularjs node.js rest


【解决方案1】:

我通过在所有路线之前添加行 app.options('*', cors()); 解决了这个问题。

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

【讨论】:

    【解决方案2】:

    您可以将解决方案设置为

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

    【讨论】:

    • the documentation 中没有关于此的内容,引用?
    • 这与文档无关,这是我们使用此解决方案为所有域启用跨域策略的正常情况。
    猜你喜欢
    • 2018-03-29
    • 2021-10-21
    • 2020-06-26
    • 2023-03-12
    • 2020-04-02
    • 2021-03-05
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    相关资源
    最近更新 更多