本文最后更新于:2024年1月14日 晚上

Node.js 中 request 模块可以发送 POST 请求,本文记录 node.js VS Code 环境配置和发送 POST 请求的方法。

背景

  • 需求是给一个url 发送post 请求,请求中加入:

    1
    2
    3
    4
    {
    "username": "your-username",
    "password": "your-password"
    }
  • 直接用 Node.js 发送 Post 请求

配置环境

安装 Node.js

配置 VS_Code

  • 安装 VS Code

  • 安装 Code Runner

  • 在项目文件夹运行

    1
    2
    3
    npm init --yes
    npm install request --save
    npm install
  • 之后可以右键运行 js 脚本

  • 也可以在代码中打断点调试

Node.js 发送 Post 请求

  • 参考代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
var request = require('request');
var url="http://111.33.44.55:8998/api/auth/login";
var requestData={
"username": "admin",
"password": "xxxxxxx"
};

httprequest(url,requestData);

function httprequest(url,data){
console.log("hello world")
request({
url: url,
method: "POST",
json: true,
headers: {
"content-type": "application/json",
},
body: requestData
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // 请求成功的处理逻辑
}else{
console.log("failed")
console.log(response.statusCode)
console.log(error)
}
});
};

参考资料



文章链接:
https://www.zywvvd.com/notes/coding/node-js/nodejs-post/nodejs-post/


“觉得不错的话,给点打赏吧 ୧(๑•̀⌄•́๑)૭”

微信二维码

微信支付

支付宝二维码

支付宝支付

Node.js 在 VS Code 中发送 POST 请求
https://www.zywvvd.com/notes/coding/node-js/nodejs-post/nodejs-post/
作者
Yiwei Zhang
发布于
2022年8月9日
许可协议