簡體   English   中英

Node-Fetch API GET with Headers

[英]Node-Fetch API GET with Headers

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命令中,它完美無缺。

讓我們使用這個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})

但是如果你想設置一些特殊的標題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", }); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM