我试图通过连接到Flask内置的RESTful API来使用JavaScript进行授权.但是,当我发出请求时,我收到以下错误:
XMLHttpRequest无法加载http:// myApiUrl/login.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此不允许原点'null'访问.
我知道API或远程资源必须设置标题,但为什么在我通过Chrome扩展程序Postman发出请求时它可以正常工作?
这是请求代码:
$.ajax({
type: "POST",
dataType: 'text',
url: api,
username: 'user',
password: 'pass',
crossDomain : true,
xhrFields: {
withCredentials: true
}
})
.done(function( data ) {
console.log("done");
})
.fail( function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
alert(textStatus);
});
Run Code Online (Sandbox Code Playgroud) 我有一个涉及的设置
前端服务器(Node.js,domain:localhost:3000)<--->后端(Django,Ajax,域:localhost:8000)
浏览器< - webapp < - Node.js(服务应用)
浏览器(webapp) - > Ajax - > Django(服务ajax POST请求)
现在,我的问题在于CORS设置,webapp使用它来向后端服务器进行Ajax调用.在chrome中,我一直在努力
当credentials标志为true时,无法在Access-Control-Allow-Origin中使用通配符.
在Firefox上也不起作用.
我的Node.js设置是:
var allowCrossDomain = function(req, res, next) {
res.header('Access-Control-Allow-Origin', 'http://localhost:8000/');
res.header('Access-Control-Allow-Credentials', true);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
};
Run Code Online (Sandbox Code Playgroud)
webapp发出如下请求:
$.ajax({
type: "POST",
url: 'http://localhost:8000/blah',
data: {},
xhrFields: {
withCredentials: true
},
crossDomain: true,
dataType: 'json',
success: successHandler
});
Run Code Online (Sandbox Code Playgroud)
因此,webapp发送的请求标头如下所示:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: "Origin, X-Requested-With, Content-Type, Accept"
Access-Control-Allow-Methods: 'GET,PUT,POST,DELETE'
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: …Run Code Online (Sandbox Code Playgroud) 如何共享cookie跨源?更具体地说,如何将Set-Cookie标题与标题结合使用Access-Control-Allow-Origin?
这是我的情况的解释:
我正在尝试localhost:4000为托管在其上的Web应用程序中运行的API设置cookie localhost:3000.
我似乎在浏览器中收到了正确的响应标题,但不幸的是它们没有任何效果.这些是响应标头:
HTTP/1.1 200 OK Access-Control-Allow-Origin: http://localhost:3000 Vary: Origin, Accept-Encoding Set-Cookie: token=0d522ba17e130d6d19eb9c25b7ac58387b798639f81ffe75bd449afbc3cc715d6b038e426adeac3316f0511dc7fae3f7; Max-Age=86400; Domain=localhost:4000; Path=/; Expires=Tue, 19 Sep 2017 21:11:36 GMT; HttpOnly Content-Type: application/json; charset=utf-8 Content-Length: 180 ETag: W/"b4-VNrmF4xNeHGeLrGehNZTQNwAaUQ" Date: Mon, 18 Sep 2017 21:11:36 GMT Connection: keep-alive
此外,Response Cookies当我使用Chrome开发者工具的"网络"标签检查流量时,我可以看到cookie .但是,我看不到在"应用程序"选项卡下设置的cookie Storage/Cookies.我没有看到任何CORS错误,所以我假设我错过了其他的东西.
有什么建议?
我正在使用React-Redux应用程序中的请求模块/signin向服务器上的端点发出请求.对于服务器我使用快递.
快递服务器:
res.cookie('token', 'xxx-xxx-xxx', { maxAge: 86400000, httpOnly: true, domain: 'localhost:3000' })
在浏览器中请求:
request.post({ uri: '/signin', json: { userName: … cors ×3
ajax ×1
cookies ×1
django ×1
http-headers ×1
javascript ×1
jquery ×1
localhost ×1
node.js ×1