在使用.delete
时需要帮助。有人告诉我,我需要在数组中找到汽车对象的索引,并使用Array.splice
删除该元素。这样做以后将在我使用Postman的响应中删除该对象。到目前为止,我已经获得了.get,.post,.patch和.use,但是我不知道如何使.delete正常工作。
到目前为止,这是我的js代码:
'use strict'
const cars = require('./cars.js')
const express = require('express')
const app = express()
app.use(express.json())
app.get('/api/cars', (req, res) => res.send({data: cars}))
app.get('/api/cars/:carId', (req, res) => {
const car = cars.find(car => car.id ===
parseInt(req.params.carId))
res.send({data: car})
})
app.post('/api/cars', (req, res) => {
const {make, model, colour} = req.body
const newCar = {
id: Date.now(),
make,
model,
colour
}
cars.push(newCar)
res.status(201).send({data: newCar})
})
app.patch('/api/cars/:carId', (req, res) => {
const id = parseInt(req.params.carId)
const index = cars.findIndex(car => car.id === carId)
if (index < 0) {
res.status(404).send({
errors: [
{
status: 'Not found',
code: '404',
title: 'Resource does not exist',
description: `We could not find a car with id: ${carId}`
}
]
})
} else {
const {id, ...theRest} = req.body
const updatedCar = Object.assign({}, cars[index], theRest)
cars[index] = updatedCar
res.send({data: updatedCar})
}
})
app.put('/api/cars/:carId', (req, res) => {
const carId = parseInt(req.params.carId)
const index = cars.findIndex(car => car.id === carId)
if (index < 0) {
res.status(404).send({
errors: [
{
status: 'Not found',
code: '404',
title: 'Resource does not exist',
description: `We could not find a car with id: ${carId}`
}
]
})
} else {
const {make, model, colour} = req.body
const updatedCar = {carId, make, model, colour}
cars[index] = updatedCar
res.send({data: updatedCar})
}
})
app.delete('/api/cars/:carId', (req, res) => {
})
const port = process.env.port || 3030
app.listen(port, () => console.log(`Server listening on port ${port} ...`))
这是我的数组中的cars.js。
const cars = [{
id: 1,
make: 'Tesla',
model: 'S',
colour: 'Black'
},
{
id: 2,
make: 'Tesla',
model: '3',
colour: 'Red'
},
{
id: 3,
make: 'Tesla',
model: 'X',
colour: 'Silver'
},
{
id: 4,
make: 'Tesla',
model: 'Y',
colour: 'Chestnut Brown'
}
]
module.exports = cars;