[Express] Level 4: Body-parser -- Post

Parser Setup

Assume the body-parser middleware is installed. Now, let‘s use it in our Express application.

npm install body-parser

Require the body-parser npm module and assign it to a variable calledbodyParser.

var bodyParser = require(‘body-parser‘);

The body-parser middleware offers different parsing options. On thebodyParser object, call a function that returns a parser for URL encoded data and store it in a variable called parseUrlencoded. Remember to pass in an option which forces the use of the native querystring Node library.

var parseUrlencoded = bodyParser.urlencoded({extended: false});
  • extended - parse extended syntax with the qs module. (default: true, but using the default has been deprecated. Please research into the difference between qs and querystring and choose the appropriate setting)

For default qs model: https://www.npmjs.org/package/qs#readme

var obj = Qs.parse(‘a=c‘);    // { a: ‘c‘ }

Read More: https://github.com/expressjs/body-parser

Mount the parser only in the post route.

app.post(‘/cities‘,parseUrlencoded, function (request, response) {
  var city;
});

Read the name and description parameters from the payload of the POSTrequest, and pass them as arguments to the createCity function (we‘ve created this one for you). Store the return value on the city variable.

app.post(‘/cities‘,parseUrlencoded, function (request, response) {
  var city, name, description;
  city = request.body;
  name = city.name;
  description = city.description;
  createCity(name, description);
});

Finally, respond back to the client with a 201 HTTP status code and the value stored in city in JSON format using json.

app.post(‘/cities‘,parseUrlencoded, function (request, response) {
  var city, name, description, cityName;
  city = request.body;
  name = city.name;
  description = city.description;
  cityName = createCity(name, description);
  response.status(201).json(cityName); //201: created
});
var express = require(‘express‘);
var app = express();
var bodyParser = require(‘body-parser‘);
var parseUrlencoded = bodyParser.urlencoded({extended: false});

app.post(‘/cities‘,parseUrlencoded, function (request, response) {
  var city, name, description, cityName;
  city = request.body;
  name = city.name;
  description = city.description;
  cityName = createCity(name, description);
  response.status(201).json(cityName); //201: created
});

app.listen(3000);

var createCity = function(name, description){
  cities[name] = description;
  return name;
};

Validation

The way that it is now, we are allowing new cities to be created with a blank description. Let‘s add some validation so that in order for a city to be created, its description must have a string length greater than 4.

Add an if block that checks for a description.length greater than 4, and move our city creation logic into that block. Use json() to send the results from createCity back to the client.

  if(request.body.description.length > 4){
    var city = createCity(request.body.name, request.body.description);
      response.status(201).json(city);
  } 

If description does not match its minimum length requirements, then set a400 status code (Bad Request) to the response, and set the response body toInvalid City using json().

app.post(‘/cities‘, parseUrlencoded, function (request, response) {

  if(request.body.description.length > 4){
    var city = createCity(request.body.name, request.body.description);
      response.status(201).json(city);
  }else{
    response.status(400).json("Invalid City"); //400: bad request
  }
});
var express = require(‘express‘);
var app = express();

var bodyParser = require(‘body-parser‘);
var parseUrlencoded = bodyParser.urlencoded({ extended: false });

app.post(‘/cities‘, parseUrlencoded, function (request, response) {

  if(request.body.description.length > 4){
    var city = createCity(request.body.name, request.body.description);
      response.status(201).json(city);
  }else{
    response.status(400).json("Invalid City"); //400: bad request
  }
});

app.listen(3000);
时间: 2024-10-09 15:11:46

[Express] Level 4: Body-parser -- Post的相关文章

[Express] Level 5: Route Instance -- refactor the code

Route Instance Let's rewrite our cities routes using a Route Instance. Create a new Route Instance for the '/cities' URL path and assign it to thecitiesRoute variable. var citiesRoute = app.route('/cities'); Move the code from our previous app.get() 

[Express] Level 5: Route file

Using a Router Instance Let's refactor app.js to use a Router object. Create a new router object and assign it to the router variable. var router = express.Router(); When we are done, our router will be mounted on the /cities path. With this in mind,

[Express] Level 2: Middleware -- 2

Logging Middleware Help finish the following middleware code in the logger.js file: On the response object, listen to the event that's emitted when the response has been handed off from Express to the underlying Operating System. response.on('finish'

[Express] Level 2: Middleware -- 1

Mounting Middleware Given an application instance is set to the app variable, which of the following function calls would you use to mount a middleware called logger ? Answer: app.use(logger); Default Middleware What is the only middleware that's shi

[Express] Level 3: Reading from the URL

City Search We want to create an endpoint that we can use to filter cities. Follow the tasks below to to create this new route. Create a new route for GET request to '/cities'. The second argument should be a callback function which takes request and

[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

[Express] Level 3: Massaging User Data

Flexible Routes Our current route only works when the city name argument matches exactly the properties in the cities object. This is a problem. We need a way to make our code more flexible. Inside our route, call the parseCityName() function passing

express框架

前面的话 Express是一个简洁.灵活的 node.js Web 应用开发框架, 它提供一系列强大的特性,帮助开发者创建各种 Web 和移动设备应用.本文将详细介绍express框架 概述 官网对Express的描述,它是一个基于 Node.js 平台,快速.开放.极简的 web 开发框架.优点是易上手.高性能.扩展性强 1.易上手:nodejs最初就是为了开发高性能web服务器而被设计出来的,然而相对底层的API会让不少新手望而却步.express对web开发相关的模块进行了适度的封装,屏蔽

node、express框架

前面的话 Express是一个简洁.灵活的 node.js Web 应用开发框架, 它提供一系列强大的特性,帮助开发者创建各种 Web 和移动设备应用.本文将详细介绍express框架 概述 官网对Express的描述,它是一个基于 Node.js 平台,快速.开放.极简的 web 开发框架.优点是易上手.高性能.扩展性强 1.易上手:nodejs最初就是为了开发高性能web服务器而被设计出来的,然而相对底层的API会让不少新手望而却步.express对web开发相关的模块进行了适度的封装,屏蔽