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

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐