zoukankan      html  css  js  c++  java
  • [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;
    }
  • 相关阅读:
    [翻译] JSAnimatedImagesView
    css3 :nth-child 常用用法
    设置屏幕亮度(系统级别和应用级别)
    nodejs 改变全局前缀
    MongoDB数据库和集合的状态信息
    NoSQL架构实践(一)——以NoSQL为辅
    socket.io,系统api,
    svn sc create 命令行创建服务自启动
    background-size background-positon合并的写法
    【转】视频编码与封装方式详解
  • 原文地址:https://www.cnblogs.com/Answer1215/p/4143533.html
Copyright © 2011-2022 走看看