我是express.js的新手,在我的一个路由中使用PUT请求更新customers数组(用作“数据库”)中的一个客户时遇到问题。请参见下面我的app.js:
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Body parser
const bodyParser = require('body-parser');
app.use(bodyParser.json());
// cors middleware
const cors = require('cors');
app.use(cors());
//const apiRouter = require('./routes/api');
//app.use('/api', apiRouter);
// get all customers
app.get('/api/customers', (req, res) => {
res.send(customers);
})
const customers = [
{
name: 'John',
id: 1,
age: 30
},
{
name: 'Mark',
id: 2,
age: 10
},
{
name: 'Andrew',
id: 3,
age: 60
}
]
/// get a customer by id
app.get('/api/customers/:id', (req, res) => {
const found = customers.some(customer => customer.id === parseInt(req.params.id));
if (found) {
res.json(customers.filter(customer => customer.id === parseInt(req.params.id)))
} else {
res.status(400).json({ msg: `No customers found with id ${req.params.id}` })
}
})
// update a customer
// look up the customer, if not found return 404, else update the customer and return the updated customer
app.put('/api/customers/:id', (req, res) => {
const customer = customers.find(c => c.id === parseInt(req.params.id));
if (!customer) {
res.status(404).res.send(`The customer with id ${req.params.id} was not found`);
} else {
customer.name = req.body.name;
customer.age = req.body.age;
res.send(customer);
}
})
app.listen(PORT, (error) => {
if (!error) {
console.log("Server is Successfully Running and App is listening on port" + PORT)
}
else {
console.log("Error occurred, server can't start", error);
}
});
module.exports = app;
我正在使用 Postman ,并试图检索更新的客户之间的现有的,但它只创建一个新的一个与他的ID,但姓名和年龄没有显示,即使在“身体”选项指定的 Postman 。我知道这可能是愚蠢的,但卡住了一段时间。任何帮助将不胜感激。
1条答案
按热度按时间a0x5cqrl1#
在路由控制器上做一个更新。在评论上试试这个,现在你看到了什么