const http = require('http');
const postData = JSON.stringify({
key1: 'value1',
key2: 'value2'
});
const options = {
hostname: 'www.example.com',
port: 80,
path: '/endpoint',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': postData.length
}
};
const req = http.request(options, (res) => {
console.log(`状态码: ${res.statusCode}`);
res.on('data', (chunk) => {
console.log(`响应主体: ${chunk}`);
});
res.on('end', () => {
console.log('响应中已无数据'); });
});
req.on('error', (error) => {
console.error(`请求遇到问题: ${error.message}`);
});
req.write(postData);
req.end();
在上述示例中,我们使用http
模块创建了一个向www.example.com
的/endpoint
路径发送POST请求的客户端。我们通过将数据转换为JSON字符串并设置适当的HTTP头来发送数据。然后,我们检查响应状态码和响应数据。
请注意,你需要替换www.example.com
和/endpoint
为你实际要发送请求的主机和路径。你还可以根据需要更改要发送的数据。