[Express] Level 4: Body-parser -- Delete
Response Body
What would the response body be set to on a DELETE request to /cities/DoesNotExist ? Here's the link to the sendStatus
function source code if you need to take a look.
Answer: 404
Delete Route
Create a Dynamic Route for deleting cities and handle for cities that are not in our list.
Create a DELETE
route that takes the city name
as its first argument, followed by a callback that takes a request
and response
objects as arguments.
app.delete('/cities/:name', function(request, response){ });
Use the built-in JavaScript operator delete
(see MDN docs) to remove the property for the city passed as an argument. Don't forget to use the attribute set in app.param()
to look the city up.
app.param('name', function (request, response, next) { request.cityName = parseCityName(request.params.name); }); app.delete('/cities/:name', function(request, response){ delete cities[request.cityName]; });
Use sendStatus()
to respond back with a status code of 200
.
app.delete('/cities/:name', function(request, response){ delete cities[request.cityName]; response.sendStatus(200); });
Add an if
block that checks whether the cityName
provided fromapp.param()
has a valid entry before attempting to delete it from thecities
object. If a valid city is not found, then respond with a 404
HTTP status code using the sendStatus()
function.
app.delete('/cities/:name', function(request, response){ if(!cities[request.cityName]){ response.sendStatus(404); }else{ delete cities[request.cityName]; response.sendStatus(200); } });
var express = require('express'); var app = express(); var cities = { 'Lotopia': 'Rough and mountainous', 'Caspiana': 'Sky-top island', 'Indigo': 'Vibrant and thriving', 'Paradise': 'Lush, green plantation', 'Flotilla': 'Bustling urban oasis' }; app.param('name', function (request, response, next) { request.cityName = parseCityName(request.params.name); }); app.delete('/cities/:name', function(request, response){ if(!cities[request.cityName]){ response.sendStatus(404); }else{ delete cities[request.cityName]; response.sendStatus(200); } }); app.listen(3000); function parseCityName(name) { var parsedName = name[0].toUpperCase() + name.slice(1).toLowerCase(); return parsedName; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具