nodeJSpost请求
时间: 2023-11-15 21:06:35 浏览: 39
在 Node.js 中发送 POST 请求可以使用内置的 `http` 或 `https` 模块,在此基础上使用 `request` 或 `axios` 等第三方模块可以使请求更加方便和灵活。
以下是使用 `http` 模块发送 POST 请求的示例代码:
```javascript
const http = require('http');
const data = JSON.stringify({
name: 'John Doe',
age: 30
});
const options = {
hostname: 'localhost',
port: 3000,
path: '/users',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': data.length
}
};
const req = http.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();
```
以上代码发送了一个 JSON 格式的数据到 localhost:3000/users,其中设置了请求的 method 为 POST,Content-Type 为 application/json,Content-Length 标识了请求体的长度。
注意:为了便于演示,以上示例代码省略了服务器端的处理逻辑。