node.js 中的 http 发送 post 请求
在本文中,我们将学习如何使用 node.js 使用第三方包发出 post 请求。
node.js 中的 http 发布请求
http post 方法在服务器上创建或添加资源。 post 和 put 请求之间的主要区别在于,通过 post 请求向服务器添加/创建新资源,而通过 put 请求更新/替换现有资源。
例如,浏览器在向服务器发送 html 表单数据或通过 jquery/ajax 请求发送数据时使用 http post 请求方法。 与 get 和 head 请求不同,http post 请求可以更改服务器的状态。
在 node.js 中发出 http 请求的不同方式
使用 axios 库
我们可以使用 axios 将异步 http 请求发送到 rest 端点。 使用 axios 执行 crud 操作变得很容易。
使用以下命令安装 axios 库。
$ npm i axios
post 请求是使用 post()
方法创建的。 当它作为第二个参数传递给 post()
函数时,axios 会自动将 javascript 对象序列化为 json。
我们不需要将 post 主体序列化为 json。
完整的源代码:
const axios = require('axios');
async function submitrequest() {
const payload = { title: 'hello world', body: 'welcome to node tutorial' };
const res = await axios.post('https://jsonplaceholder.typicode.com/posts', payload);
const data = res.data;
console.log(data);
}
submitrequest();
在上面的示例中,一旦用户提交了表单,post 调用就会发送到带有指定 url(本文中为虚拟)和参数的节点服务器。 如果服务器不间断地处理这些数据,它会返回一条成功消息。
根据服务器响应的输出,您可以在控制台上打印消息或通过消息通知用户。
输出:
{
title: 'hello world',
body: 'welcome to node tutorial',
id: 101
}
使用 node 获取库
我们可以使用 node-fetch 库将异步 http 请求发送到 rest 端点。 我们可以在此处找到有关节点提取的更多信息。
使用以下命令安装节点获取库。
$ npm i node-fetch
完整的源代码:
const fetch = require('node-fetch');
async function gettododata() {
const payload = { title: 'hello world', body: 'welcome to node tutorial' };
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'post',
body: json.stringify(payload),
headers: {'content-type': 'application/json'}
});
const data = await response.json();
console.log(data);
}
gettododata();
输出结果如下:
{
title: 'hello world',
body: 'welcome to node tutorial',
id: 101
}
使用 superagent 库
让我们使用 superagent 库在 node.js 中发出 http post 请求。 我们可以在此处找到有关 superagent 库的更多信息。
使用以下命令安装 superagent 库。
$ npm i superagent
完整的源代码:
const superagent = require('superagent');
async function gettododata() {
const payload = { title: 'hello world', body: 'welcome to node tutorial' };
const res = await superagent.post('https://jsonplaceholder.typicode.com/posts').send(payload);
console.log(res.body);
}
gettododata();
输出结果如下:
{
title: 'hello world',
body: 'welcome to node tutorial',
id: 101
}
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
发布时间:2023/03/27 浏览次数:243 分类:node.js
-
本教程演示了如何在 node js 中使用 module.exports。
node.js 与 react js 的比较
发布时间:2023/03/27 浏览次数:173 分类:node.js
-
本文比较和对比了两种编程语言,node.js 和 react。react 和 node.js 都是开源 javascript 库的示例。 这些库用于构建用户界面和服务器端应用程序。