如何使用node.js和Request包禁用HTTP头中的“withcredentials”?
从浏览器(通过browserify )使用node.js和Request包,我使用CORS在单独的域上执行HTTP GET请求。
在服务器上,当我将'Access-Control-Allow-Origin'
设置为通配符'*'
,客户端上出现以下错误:
XMLHttpRequest无法加载….当凭证标志为真时,通配符“*”不能在“Access-Control-Allow-Origin”标头中使用。 原因'…'因此不被允许访问。
HTTP请求标题如下所示:
Accept:*/* Accept-Encoding:gzip,deflate,sdch Accept-Language:en-US,en;q=0.8,ja;q=0.6 Access-Control-Request-Headers:withcredentials Access-Control-Request-Method:GET Cache-Control:no-cache Connection:keep-alive Host:localhost:3000 Origin:http://localhost:9966 Pragma:no-cache Referer:http://localhost:9966/ User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
所以清楚的问题是Access-Control-Request-Headers:withcredentials
在头文件中Access-Control-Request-Headers:withcredentials
,对不对?
为了能够删除这个,我需要将'XMLHttpRequest'对象的'withcredentials'属性设置为'false'。 然而,我无法弄清楚node.js或Request包在创build“XMLHttpRequest”对象,我甚至可以访问它。
谢谢。
经过一番调查,我发现可以通过options参数对象传入withCredentials
设置:
var req = http.request({ withCredentials: false }, function(res) { //... }); req.end();
如果undefined
,则默认设置为true
。
来自http-browserify/lib/request.js
源文件的引用:
if (typeof params.withCredentials === 'undefined') { params.withCredentials = true; } try { xhr.withCredentials = params.withCredentials } catch (e) {}