https://www.npmjs.com/package/node-fetch Node v6.4.0 npm v3.10.3
我想在此 API 调用中发送带有自定义 header 的 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)
})
header 不适用,我被拒绝访问。 但在 curl 命令中,它可以完美运行。
最佳答案
让我们使用这个 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
两个 \r\n
实际上是不可见的 CRLF,规范说,它们标记 header 的结尾和请求正文的开头。您可以在控制台中看到额外的新行。
现在,如果您希望它看起来像这样:
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
那么你只需要一点零钱:
// var headers = {}
//headers['This-Api-Header-Custom'] = {
var headers = {
Username: loginInformation.username,
Password: loginInformation.password,
requiredApiKey: loginInformation.ApiKey
}
fetch(server, { method: 'GET', headers: headers})
但是如果你想设置一些特殊的header This-Api-Header-Custom
,那么你不能传入嵌套对象和数组,但是你必须序列化你的数据,即转用户名/password/requiredApiKey 数据转换成字符串。根据您的要求,这可能是例如CSV、JSON、...
关于node.js - 带有 header 的 Node 获取 API GET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40099282/