我正在尝试oauth使用angular - > node - > twitter进行推特但是我在向混音添加角度时不断得到错误No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access
。我的应用配置..
使用调用呼叫快速路由的快速模板可以正常工作,如下所示
template - > localhost:3000 / auth / twitter
Response Headers
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:4200
Location:https://api.twitter.com/oauth/authenticate?oauth_token=placeholdertokenstackoverflow
Vary:Origin
Request Headers
Host:localhost:3000
Referer:http://localhost:3000/
localhost:3000 / auth / twitter - > //api.twitter.com/oauth / ...
GENERAL
Request URL:https://api.twitter.com/oauth/authenticate?oauth_token=placeholdertokenstackoverflow
Request Method:GET
Status Code:200
Request Headers
:authority:api.twitter.com
:method:GET
:scheme:https
referer:http://localhost:3000/
当使用angular来调用express路由而不是模板时,我认为是一个CORS错误,如下所示
angular.http.get - > localhost:3000 / auth / twitter
RESPONSE HEADERS
Access-Control-Allow-Credentials:true
Access-Control-Allow-Origin:http://localhost:4200
Location:https://api.twitter.com/oauth/authenticate?oauth_token=placeholdertokenstackoverflow
Vary:Origin
REQUEST HEADERS
Host:localhost:3000
Origin:http://localhost:4200
Referer:http://localhost:4200/
localhost:3000 / auth / twitter - > //api.twitter.com/oauth / ...
GENERAL
Request URL:https://api.twitter.com/oauth/authenticate?oauth_token=placeholdertokenstackoverflow
Request Method:GET
Status Code:200
REQUEST HEADERS
:authority:api.twitter.com
:method:GET
:scheme:https
***origin:null
referer:http://localhost:4200/***
当角度调用快速路线时,看上面origin:null
。即使Express服务器在两个实例中都设置相同并调用twitter,但标题是不同的,我不明白。角度设置视图而不是表达会使浏览器对请求的来源感到困惑吗?
修改节点服务器以添加标头Access-Control-Allow-Origin:*以从任何地方启用跨源请求(或指定域而不是*)。这应该可以解决您的问题。以下是我解决问题的方法:
const app = express()
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content-Type, Accept"
);
next();
});
如果你使用Express,你可以尝试这个cors package。
编辑:
var express = require('express')
var cors = require('cors')
var app = express()
app.use(cors())
app.get('/products/:id', function (req, res, next) {
res.json({msg: 'This is CORS-enabled for all origins!'})
})
app.listen(80, function () {
console.log('CORS-enabled web server listening on port 80')
})