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()
PS:笔者曾经在使用http与https库的过程中,遇到过不同协议的报错问题,于是做了一个简单的替换,如上述代码中,使用了:
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的协议类型就可以自动调用相应的模块。
- nodejs处理http请求实例详解之get和post
- Node.js中的HTTP Server对象与GET、POST请求
- nodejs 使用http进行post或get请求的实例(携带cookie)
- nodejs使用http模块发送get与post请求的方法示例
- nodejs实现HTTPS发起POST请求
- node.js+postman实现模拟HTTP服务器与客户端交互
- 从零开始学习Node.js系列教程一:http get和post用法分析
- 轻松创建nodejs服务器(10):处理POST请求
- nodejs之get/post请求的几种方式小结
- Node.js如何响应Ajax的POST请求并且保存为JSON文件详解
- NodeJS收发GET和POST请求的示例代码
相关文章
Nodejs中Express 常用中间件 body-parser 实现解析
这篇文章主要介绍了Nodejs中Express 常用中间件 body-parser 实现解析,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05node.js对于数据库MySQL基本操作实例总结【增删改查】
这篇文章主要介绍了node.js对于数据库MySQL基本操作,结合实例形式总结分析了node.js针对mysql数据库基本配置、连接与增删改查相关操作技巧,需要的朋友可以参考下2023-04-04
最新评论