博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Express] Level 4: Body-parser -- Delete
阅读量:4993 次
发布时间:2019-06-12

本文共 2288 字,大约阅读时间需要 7 分钟。

Response Body

What would the response body be set to on a DELETE request to /cities/DoesNotExist ? Here's  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 () 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;}

 

转载于:https://www.cnblogs.com/Answer1215/p/4143533.html

你可能感兴趣的文章
【转】字符串和浮点数格式化输出小结
查看>>
Android开发 - Retrofit 2 使用自签名的HTTPS证书进行API请求
查看>>
对测试人员或开发人员来说相互沟通有多重要?
查看>>
解释器、编译器以及他们之间的差别。
查看>>
MongoDB的快速手动安装
查看>>
JS制作简单的日历控件【JS Date对象操作实例演示】
查看>>
模板—树上倍增LCA
查看>>
高二小假期集训—D5
查看>>
EasyUI easyui-combobox 重复发送请求
查看>>
memcached-repcached
查看>>
[转]CentOS 5.3通过yum升级php到最新版本的方法
查看>>
UVA 11235 - Frequent values RMQ的应用
查看>>
大数据日志采集系统
查看>>
java 堆调优
查看>>
linux 安装JDK
查看>>
JAVA调用CMD命令
查看>>
weblogic的安装
查看>>
SSM框架中,controller的action返回参数给vue.js
查看>>
Mysql 基础3
查看>>
smartctl工具应用(转载整理)
查看>>