node.js - 带有 header 的 Node 获取 API GET

标签 node.js api

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/

相关文章:

linux - npm 安装出错

api - Facebook 图形 API 速率限制和批量请求

json - Wordpress Json API 缓存

javascript - REST - Rails API 前端

ajax - 如何使用 Node 将 HTML POST 与 Mongodb 连接

node.js 错误处理。将错误消息存储在 err 中,而不是自动将其打印到控制台

javascript - 带有Angular的ASP.NET Core上的级联下拉列表

java - 如何使用 Java 获取 AzureRateCard?

javascript - 循环遍历 mp3 文件名数组并将 id3 标签提取到 nodejs 中的另一个数组中

node.js - 在像 AWS lambda 这样的无状态 FaaS 上使用 PostgreSQL 是个好主意吗?