1. 程式人生 > 實用技巧 >nodejs.cn-Node.js-入門教程:使用 Node.js 傳送 HTTP POST 請求

nodejs.cn-Node.js-入門教程:使用 Node.js 傳送 HTTP POST 請求

ylbtech-nodejs.cn-Node.js-入門教程:使用 Node.js 傳送 HTTP POST 請求

1.返回頂部
1、

使用 Node.js 傳送 HTTP POST 請求

在 Node.js 中,有多種方式可以執行 HTTP POST 請求,具體取決於要使用的抽象級別。

使用 Node.js 執行 HTTP 請求的最簡單的方式是使用Axios 庫

const axios = require('axios')

axios
  .post('http://nodejs.cn/todos', {
    todo: '做點事情'
  })
  .then(res => {
    console.log(`狀態碼: ${res.statusCode}`)
    console.log(res)
  })
  .catch(error => {
    console.error(error)
  })

Axios 需要使用第三方的庫

也可以只使用 Node.js 的標準模組來發送 POST 請求,儘管它比前面的選擇冗長些:

const https = require('https')

const data = JSON.stringify({
  todo: '做點事情'
})

const options = {
  hostname: 'nodejs.cn',
  port: 443,
  path: '/todos',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': data.length
  }
}

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.write(data)
req.end()
2、
2.返回頂部
3.返回頂部
4.返回頂部
5.返回頂部
1、 http://nodejs.cn/learn/make-an-http-post-request-using-nodejs 2、
6.返回頂部
作者:ylbtech
出處:http://ylbtech.cnblogs.com/
本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。