node.js - 如何使用 Node 和 ExpressJS 库进行 POST 调用
问题描述
我正在使用 NodeJS 开发 Express 来构建一些自定义 API。我已经成功构建了一些 API。使用 GET,我能够检索数据。
这是我的 index.js 文件,其中包含所有代码。
const express = require('express');
const app = express();
//Create user data.
const userData = [
{
id : 673630,
firstName : 'Prasanta',
lastName : 'Banerjee',
age : 24,
hobby : [
{
coding : ['java', 'python', 'javascript'],
movies : ['action', 'comedy' , 'suspense'],
sports : "basketball"
}
],
oper_sys : ['Mac', 'Windows']
},
{
id : 673631,
firstName : 'Neha',
lastName : 'Bharti',
age : 23
},
{
id : 673651,
firstName : 'Priyanka',
lastName : 'Moharana',
age : 24
},
{
id : 673649,
firstName : 'Shreyanshu',
lastName : 'Jena',
age : 25
},
{
id : 673632,
firstName : 'Priyanka',
lastName : 'Sonalia',
age : 23
},
{
id : 673653,
firstName : 'Bhupinder',
lastName : 'Singh',
age : 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function(req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function(req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if(user){
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({Error: ['ID Not Found']});
}
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function() {
console.log('Your server is up & running at localhost:'+PORT+'. Please hit the APIs.');
});
假设我想将 id:12345 firstName:Michael lastName:Andrews 添加到我的 userData 中。我应该如何使用 POST 调用?
我正在寻找可以将新数据添加到我的 userData 的代码,这样每次我对它执行 GET 操作时,我都会得到更新的数据集。
解决方案
为了根据请求发送 POST 数据,您必须通过请求正文传递数据。为此,您必须安装一个名为body-parser的 Node.js 正文解析中间件。请阅读本文以了解如何在您的应用程序上进行配置。
然后你必须将 POST 路由和方法添加到你的 app.js 文件中。然后通过 body 解析数据来命中路由。我已经编辑了您的代码并将其发布在下面。我已经评论了我添加方法和中间件的地方。
const express = require('express');
const app = express();
// require body parser middleware
const bodyParser = require('body-parser')
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
//Create user data.
const userData = [
{
id: 673630,
firstName: 'Prasanta',
lastName: 'Banerjee',
age: 24,
hobby: [
{
coding: ['java', 'python', 'javascript'],
movies: ['action', 'comedy', 'suspense'],
sports: "basketball"
}
],
oper_sys: ['Mac', 'Windows']
},
{
id: 673631,
firstName: 'Neha',
lastName: 'Bharti',
age: 23
},
{
id: 673651,
firstName: 'Priyanka',
lastName: 'Moharana',
age: 24
},
{
id: 673649,
firstName: 'Shreyanshu',
lastName: 'Jena',
age: 25
},
{
id: 673632,
firstName: 'Priyanka',
lastName: 'Sonalia',
age: 23
},
{
id: 673653,
firstName: 'Bhupinder',
lastName: 'Singh',
age: 25
},
];
//Create the API endpoints with callback functions.
//Display all Employees data.
app.get('/api/employees', function (req, res) {
res.json(userData);
});
//Display employee data based on 'id' param.
app.get('/api/employees/:id', function (req, res) {
const id = req.params.id;
const user = userData.find(user => user.id == id)
if (user) {
res.statusCode = 200
res.json(user)
}
else {
res.statusCode = 404
return res.json({ Error: ['ID Not Found'] });
}
});
// POST emplyee data
app.post('/api/employees/', function (req, res) {
// catch request body data, break it down and assign it to a variable
// you can just parse req.body as well
const newUser = {
id: req.body.id,
firstName: req.body.firstName,
lastName: req.body.lastName
}
userData.push(newUser);
res.status(200).json(newUser);
});
//start the node server.
const PORT = 7777;
app.listen(PORT, function () {
console.log('Your server is up & running at localhost:' + PORT + '. Please hit the APIs.');
});
推荐阅读
- codeigniter - 带字段循环的codeigniter字段提交
- c# - DialogContext.BeginDialogAsync() 如何使用构造参数开始对话
- php - 如果刀片中的连接表中有 user_id 字段,如何获取用户名
- java - 压缩子目录是只压缩子目录的内容,而不是子目录
- laravel - laravel-5.8:在 laravel 中显示更改格式的日期
- python - 在 PyQt 应用程序中将 reactor.run() 放在哪里?
- javascript - Heroku Node.js 应用程序拒绝应用样式,因为它的 MIME 类型
- rust - Rust std::net::UdpSocket 没有名为 recv_from 的方法
- python - 在 python 中使用 mplot3d 绘制透明平面
- java - 如何在不删除配置单元表的情况下基于 DataFrame 从 SparkSQL 更改表,例如删除/添加列?