javascript - 如何使用 node.js 和请求包禁用 HTTP header 中的 'withcredentials'?

标签 javascript node.js http xmlhttprequest request

使用 node.js 和 Request从浏览器打包(通过 browserify ),我正在使用 CORS 在单独的域上执行 HTTP GET 请求。

在服务器上,当我将 'Access-Control-Allow-Origin' 设置为通配符 '*' 时,客户端出现以下错误:

XMLHttpRequest cannot load .... A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin '...' is therefore not allowed access.

HTTP 请求 header 如下所示:

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

很明显,问题在于 header 中的 Access-Control-Request-Headers:withcredentials,对吧?

为了能够删除它,我需要将“XMLHttpRequest”对象的“withcredentials”属性设置为“false”。但是,我无法弄清楚 node.js 或 Request 包在哪里创建“XMLHttpRequest”对象,以及如何访问它。

谢谢。

最佳答案

经过一番调查,我发现withCredentials设置可以通过options参数对象传入:

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) {}

关于javascript - 如何使用 node.js 和请求包禁用 HTTP header 中的 'withcredentials'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24433099/

相关文章:

javascript - 如何等到道场的元素存在?

javascript - req.session 在 Node 中未定义?

javascript - 在 Express 服务器上启用 HTTPS

javascript - 来自另一个模块所需的模块的node.js proxyquire stub 异步函数

javascript - 在Javascript中每10位输入一个逗号?

javascript - 外部 .js 文件中的 JQuery 未运行

node.js - 当真正的 sequelize 连接在 require 树中时,为什么这个 sequelize-test-helper 调用不起作用?

linux - 错误 403 : Forbidden

android - 在 Android 应用程序中设置 URL?

rest - 将 API key 放在 header 或 URL 中