【问题标题】:How to disable 'withCredentials' in api call using node.js only (https package)如何仅使用 node.js(https 包)在 api 调用中禁用“withCredentials”
【发布时间】:2016-12-31 00:37:20
【问题描述】:

我正在使用加载内置 https 包的 node.js 脚本。使用时出现错误:

XMLHttpRequest cannot load [constructed-api-url]. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

我使用的是 node.js 4.4.3,它的 https api docs 并没有真正提及 withCredentials 的任何内容。

正在使用的脚本是this one

是否可以使用 node.js https 将 xhr 调用的 withCredentials 设置为 false?

我正在寻找类似于这个 jquery ajax 调用的东西(只关注 xhr 字段):

$.ajax({
            type: 'POST',  async:true,
            url: 'https://someapp.constructed.url/token',
            dataType: "json",
            contentType: 'application/x-www-form-urlencoded; charset=utf-8',
            xhrFields: {
                withCredentials: true
            },
            headers: {
                'Authorization': 'Basic ' + appInfo                    
            },              
            success: function (result) {
                var token = result.access_token;
                //…                   
            },
            error: function (req, status, error) {
                if (typeof(req) != 'undefined') {
                    var msg = status || req.responseJSON.error;
                    //…
                }                   
            }
    });

还有一个非常类似的例子,不过这和请求包有关,我不想包含在依赖中。此外,我使用的脚本已经在使用 https。

【问题讨论】:

  • 这是浏览器错误,与节点无关。
  • @AlexeyTen:当然不是节点的错,但是从 jquery ajax 示例中可以看出,可以从请求代码中设置特定的 xhr 标志。这可以从 node.js 的 https 模块完成吗?
  • 节点不关心这个标志。您应该在浏览器中执行的 JS 代码中查找它。

标签: javascript node.js xmlhttprequest cors


【解决方案1】:

所以答案一直都在那里,毕竟:

经过一番研究,发现 node 的 https 包使用与 http 几乎相同的选项,包括 withCredentials 选项(在 node 的 http/https 中没有记录,但 xhr 文档的一部分)。问题是将url 选项与withCredentials 选项一起包含在选项对象中,然后将options 对象作为https.get 的参数传递。

并且构造的代码或多或少如下(关注options变量):

var options = {
  url: 'https://my.domain.com/api/endpoint',
  withCredentials: false  
}
var querystring = '?key=' + [_my_api_key];
var param1 = '&' + [paramKey] + '=' + [paramValue];

var datos;

options.url += querystring;
options.url += param1;

https.get(options, function (res) {
  res.on('data', function (data) {
    datos += data;
  });

  res.on('end', function () {      
    try {
      var data = JSON.parse(datos);
    } catch (e) {
      console.error('Unable to parse response as JSON', e);
    }
  });
}).on('error', function (e) {
    console.error('An error occurred with the request:', e.message);
    callback(e.message);
});

【讨论】:

    猜你喜欢
    • 2014-08-17
    • 2020-08-19
    • 2014-05-24
    • 2018-01-31
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2019-12-08
    • 2020-10-04
    相关资源
    最近更新 更多