【问题标题】:Node-Fetch API GET with Headers带有标头的 Node-Fetch API GET
【发布时间】:2017-02-27 04:45:46
【问题描述】:

https://www.npmjs.com/package/node-fetch 节点 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)
})

标题不适用,我被拒绝访问。 但是在 curl 命令中,它可以完美运行。

【问题讨论】:

标签: node.js api


【解决方案1】:

我认为您需要使用 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",
});

【讨论】:

  • 我很好奇你从哪里拉取 Node.js 中的 Web Header 接口。
  • const { Headers } = require('node-fetch');
【解决方案2】:

让我们使用这个 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,它们标记了标头的结尾和请求正文的开头。您可以在控制台中看到额外的新行。 现在,如果您希望它看起来像这样:

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

但是如果你想设置一些特殊的headerThis-Api-Header-Custom,那么你不能传入嵌套对象和数组,但是你必须序列化你的数据,即将username/password/requiredApiKey数据变成一个字符串。根据您的要求,这可能是例如CSV、JSON、...

【讨论】:

    猜你喜欢
    • 2021-08-01
    • 1970-01-01
    • 2015-04-19
    • 2019-05-18
    • 2023-03-13
    • 2021-07-22
    • 2013-11-09
    • 2014-09-15
    相关资源
    最近更新 更多