![](/img/trans.png)
[英]How to disable 'withcredentials' in HTTP header with node.js and Request package?
[英]How to disable 'withCredentials' in api call using node.js only (https package)
我正在使用一個加載內置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文檔中並未真正提及有關withCredentials的任何內容。
正在使用的腳本是此腳本。
無論如何,使用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。
畢竟答案一直存在:
經過一番研究,發現該節點的https軟件包實際上使用了與http相同的選項,包括withCredentials
選項(未在節點的http / https中進行記錄,而是xhr文檔的一部分)。 只需將url
選項和withCredentials
選項一起包含在options對象中,然后將options
對象作為https.get
參數傳遞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);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.