node发送post请求_使用Node发出HTTP POST请求

node发送post请求

There are many ways to perform an HTTP POST request in Node, depending on the abstraction level you want to use.

有多种方法可以在Node中执行HTTP POST请求,具体取决于您要使用的抽象级别。

The simplest way to perform an HTTP request using Node is to use the Axios library:

使用Node执行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()

转:https://blog.csdn.net/cuk0051/article/details/108341785

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值