// 引入 http 模块
const http = require('http');
const querystring = require('querystring');
// 创建 POST 请求的选项
const postOptions = {
host: 'www.example.com', // 请求的目标域名或 IP 地址
port: 80, // 目标服务器端口
path: '/path', // 请求路径
method: 'POST', // 请求方法
headers: { // 请求头信息
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
// 要发送的数据
const postData = querystring.stringify({
key1: 'value1',
key2: 'value2'
});
// 创建请求对象
const req = http.request(postOptions, (res) => {
let data = '';
// 接收响应数据
res.on('data', (chunk) => {
data += chunk;
});
// 响应结束时处理数据
res.on('end', () => {
console.log('Response:', data);
});
});
// 发生错误时输出错误信息
req.on('error', (e) => {
console.error(`请求遇到问题: ${e.message}`);
});
// 写入数据到请求体
req.write(postData);
// 结束请求
req.end();
http 和 querystring 模块,http 模块用于创建 HTTP 请求,querystring 模块用于将 JavaScript 对象序列化为 URL 编码格式。postOptions 包含了目标服务器的地址、端口、路径、HTTP 方法和请求头信息。特别地,Content-Length 是根据要发送的数据长度设置的。querystring.stringify 将 JavaScript 对象转换为 URL 编码字符串,并赋值给 postData。http.request 创建一个 HTTP 请求对象,并监听响应事件(如 data 和 end)。如果有错误发生,会触发 error 事件。req.write 向请求体中写入数据,并调用 req.end 结束请求。下一篇:js object.keys()
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站