首頁 > 軟體

Node.js 中使用fetch 按JSON格式發post請求的問題解析

2023-04-02 06:01:03

Node.js 中使用fetch 按JSON格式發post請求

最近在測試一個api,可以用curl命令直接存取,指定header相關設定,request body(JSON),成功後返回一個JSON。

原本想搞個靜態頁面html,在script標籤裡用fetch做個簡單的demo的,結果就遇到跨域問題。遂使用後端請求,就想到了Nodejs。

既然有現成的工具,那就使用唄。

環境node --version: 18.15.0

1.全域性安裝express-generator:

npm i express-generator -g

2.生成一個測試專案:

express nodepost

3. 安裝依賴

cd nodepostnpm install

4.試執行(沒有意外的話可以在瀏覽器輸入 localhost:3000,看到Express 歡迎頁)

npm start

5. VSCODE編輯

code .

6.修改routers/index.js, 增加以下程式碼段,注意按你實際設定來(url, requestData, authkey...)

router.get('/json', (req, res, next) => {
  let success = true;
  const data = {
    k: 'your real data'
  };
  fetch('https://example.com/api/g', {
    method: 'POST',
    body: JSON.stringify(data),
    headers: {
      'Content-type': 'application/json; charset=UTF-8',
      'Authorization': 'your real auth key if neccessory, otherwise you could not config this item',
 
    },
  }
  ).then((res) => res.json())
  .then((json) => console.log(json))
  .catch(err => {
    success = false;
    console.log('err:', err);
  })
  res.json({
    success
  })
});

7.存取 localhost:3000/json, 不出問題的話能在後端控制檯檢視請求結果

PLUS:

選擇新版本的Node,不能低於17.5.0,否則不能直接使用fecth,在文末有補充說明。

低版本用node-fetch庫或者原生的http模組, node-fetch我自己匯入一直有問題,原生http模組要寫不少東西,故不採用。

補充:寫 Node.js,終於能用 Fetch 發請求了

Node.js 支援 Fetch API 啦!

在以前,使用原生的 Node.js API 傳送一個 HTTP 請求非常麻煩,你可能要寫下面的程式碼:

const https = require('https')
const options = {
  hostname: 'nodejs.cn',
  port: 443,
  path: '/todos',
  method: 'GET'
}
 
const req = https.request(options, res => {
  console.log(`狀態碼: ${res.statusCode}`)
 
  res.on('data', d => {
    process.stdout.write(d)
  })
})
 
req.on('error', error => {
  console.error(error)
})
 
req.end()

所以通常,我們可能會引入一些第三方的 NPM 包,比如 axios、needle、node-fetch、request 這些。

在最新的 Node.js v17.5 版本中,增加了對 Fetch API 的支援,所以無需藉助這些第三方 HTTP 請求庫啦。

Fetch API 可能大家都比較熟悉了,他是當前最流行的跨平臺 HTTP Client API ,目前已經可以在瀏覽器和 Web/Service Workers 中執行,當前 Web 環境裡用到最多的請求方式應該就是它了。

Node.js 中的Fetch API 基於 Undici 實現,它提供了一個 WHATWG 標準介面來獲取資源,並且也是基於 Promise 的,使用方式基本和瀏覽器中一致,包括四個核心模組:

  • fetch() - 用於發起請求的函數
  • Headers 類 - 用於處理請求頭和響應頭
  • Request 類 - 表示傳入請求的範例
  • Response 類 - 表示傳入響應的範例
const res = await fetch('https://www.conardli.top');
const json = await res.json();
console.log(json);

其實這並不是簡單的支援了一個新的原生 HTTP 請求庫那麼簡單,這意味著很多之前在 Web 中用到 FetchNPM 包也可以在 Node.js 裡以同樣的方式工作了,這些包同樣可以實現跨平臺相容了~

Node.js v17.5 中,它還是個實驗特性,現在想要試用的話可以通過 node --experimental-fetch flag 開啟。

Fetch 的優勢在於它是原生支援,並且可以相容多平臺,其他的請求庫估計都要慢慢的靠邊站了~ 對此你有啥看法?

到此這篇關於Node.js 中使用fetch 按JSON格式發post請求的文章就介紹到這了,更多相關Node.js fetch post請求內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com