https://www.npmjs.com/package/node-fetch Node v6.4.0 npm v3.10.3
我想在此 API 调用中发送带有自定义标头的 GET 请求。
const fetch = require('node-fetch')
var server = 'https://example.net/information_submitted/'
var loginInformation = {
username: "example@example.com",
password: "examplePassword",
ApiKey: "0000-0000-00-000-0000-0"
}
var headers = {}
headers['This-Api-Header-Custom'] = {
Username: loginInformation.username,
Password: loginInformation.password,
requiredApiKey: loginInformation.ApiKey
}
fetch(server, { method: 'GET', headers: headers})
.then((res) => {
console.log(res)
return res.json()
})
.then((json) => {
console.log(json)
})
Run Code Online (Sandbox Code Playgroud)
标题不适用,我被拒绝访问。但是在 curl 命令中,它可以完美运行。
Ivi*_*ilo 10
让我们使用这个 bash 命令netcat -lp 8081并将 url 临时更改为http://localhost:8081/testurl. 现在,请求仍然会失败,但我们的控制台会显示一些原始请求数据:
user@host:~$ netcat -lp 8081
GET /testurl HTTP/1.1
accept-encoding: gzip,deflate
user-agent: node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
connection: close
accept: */*
Host: localhost:8081\r\n
\r\n
Run Code Online (Sandbox Code Playgroud)
\r\n规范说,这两个实际上是不可见的 CRLF,它们标志着标头的结束和请求正文的开始。您可以在控制台中看到额外的新行。现在,如果您希望它看起来像这样:
user@host:~$ netcat -lp 8081
GET /testurl HTTP/1.1
username: example@example.com
password: examplePassword
requiredapikey: 0000-0000-00-000-0000-0
accept-encoding: gzip,deflate
user-agent: node-fetch/1.0 (+https://github.com/bitinn/node-fetch)
connection: close
accept: */*
Host: localhost:8081
Run Code Online (Sandbox Code Playgroud)
那么你只需要一点点改变:
// var headers = {}
//headers['This-Api-Header-Custom'] = {
var headers = {
Username: loginInformation.username,
Password: loginInformation.password,
requiredApiKey: loginInformation.ApiKey
}
fetch(server, { method: 'GET', headers: headers})
Run Code Online (Sandbox Code Playgroud)
但是如果你想设置一些特殊的 header This-Api-Header-Custom,那么你不能传入嵌套的对象和数组,而是你必须序列化你的数据,即将用户名/密码/requiredApiKey 数据转换为字符串。根据您的要求,这可能是例如 CSV、JSON、...
我认为您需要使用 Headers 构造函数,而不是普通对象。
https://developer.mozilla.org/en-US/docs/Web/API/Headers
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Headers
myHeaders = new Headers({
"Content-Type": "text/plain",
"Content-Length": content.length.toString(),
"X-Custom-Header": "ProcessThisImmediately",
});Run Code Online (Sandbox Code Playgroud)