首页 > 编程知识 正文

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

时间:2023-05-04 21:19:18 阅读:221962 作者:2814

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://flaviocopes.com/node-http-post/

node发送post请求

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。