Node發(fā)出HTTP POST請求的方法實例小結(jié)
node發(fā)送post請求
There are many ways to perform an HTTP POST request in Node, depending on the abstraction level you want to use.
有多種方法可以在Node中執(zhí)行HTTP POST請求,具體取決于您要使用的抽象級別。
The simplest way to perform an HTTP request using Node is to use the Axios library:
使用Node執(zhí)行HTTP請求的最簡單方法是使用Axios庫 :
const axios = require('axios') axios.post('https://flaviocopes.com/todos', { ? todo: 'Buy the milk' }) .then((res) => { ? console.log(`statusCode: ${res.statusCode}`) ? console.log(res) }) .catch((error) => { ? console.error(error) }
Another way is to use the Request library:
另一種方法是使用Request庫 :
const request = require('request') request.post('https://flaviocopes.com/todos', { ? json: { ? ? todo: 'Buy the milk' ? } }, (error, res, body) => { ? if (error) { ? ? console.error(error) ? ? return ? } ? console.log(`statusCode: ${res.statusCode}`) ? console.log(body) }
The 2 ways highlighted up to now require the use of a 3rd party library.
到目前為止突出顯示的2種方式都需要使用第三方庫。
A POST request is possible just using the Node standard modules, although it’s more verbose than the two preceding options:
POST請求僅使用Node標準模塊是可能的,盡管它比前面兩個選項更冗長:
const https = require('https') const data = JSON.stringify({ ? todo: 'Buy the milk' }) const options = { ? hostname: 'flaviocopes.com', ? port: 443, ? path: '/todos', ? method: 'POST', ? headers: { ? ? 'Content-Type': 'application/json', ? ? 'Content-Length': data.length ? } } const req = https.request(options, (res) => { ? console.log(`statusCode: ${res.statusCode}`) ? res.on('data', (d) => { ? ? process.stdout.write(d) ? }) }) req.on('error', (error) => { ? console.error(error) }) req.write(data) req.end()
PS:筆者曾經(jīng)在使用http與https庫的過程中,遇到過不同協(xié)議的報錯問題,于是做了一個簡單的替換,如上述代碼中,使用了:
const req = https.request(options, (res) => { .... })
筆者對此做了如下的修改:
let mod = null;//http、https 別名 if(url.indexOf('https://')!==-1){ ? ? mod = https; }else{ ? ? mod = http; } const req = mod.request(options, (res) => { .... })
此時,針對URL的協(xié)議類型就可以自動調(diào)用相應(yīng)的模塊。
- nodejs處理http請求實例詳解之get和post
- Node.js中的HTTP?Server對象與GET、POST請求
- nodejs 使用http進行post或get請求的實例(攜帶cookie)
- nodejs使用http模塊發(fā)送get與post請求的方法示例
- nodejs實現(xiàn)HTTPS發(fā)起POST請求
- node.js+postman實現(xiàn)模擬HTTP服務(wù)器與客戶端交互
- 從零開始學習Node.js系列教程一:http get和post用法分析
- 輕松創(chuàng)建nodejs服務(wù)器(10):處理POST請求
- nodejs之get/post請求的幾種方式小結(jié)
- Node.js如何響應(yīng)Ajax的POST請求并且保存為JSON文件詳解
- NodeJS收發(fā)GET和POST請求的示例代碼
相關(guān)文章
nodejs實現(xiàn)獲取本地文件夾下圖片信息功能示例
這篇文章主要介紹了nodejs實現(xiàn)獲取本地文件夾下圖片信息功能,涉及node.js針對文件、目錄的遍歷、讀取等相關(guān)操作技巧,需要的朋友可以參考下2019-06-06NestJS開發(fā)核心概念Providers類基本用法詳解
這篇文章主要為大家介紹了NestJS開發(fā)核心概念Providers類基本用法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-08-08node.js中的querystring.parse方法使用說明
這篇文章主要介紹了node.js中的querystring.parse方法使用說明,本文介紹了querystring.parse的方法說明、語法、接收參數(shù)、使用實例和實現(xiàn)源碼,需要的朋友可以參考下2014-12-12