[toc]

Introduction to the

Nodejs, as an excellent asynchronous IO framework, is itself used as HTTP Web server. The HTTP module in NodeJS provides many very useful HTTP related functions.

Nodejs already has HTTP processing modules, but that may not be enough for modern Web applications, so we have the Express framework to extend nodeJS content.

Today we will look at the differences between developing Web applications using NodeJS and Express.

Build HTTP Web services using NodeJS

Nodejs provides HTTP modules that can be easily used to create a Web service:

const http = require('http')

const hostname = '127.0.0.1'
const port = 3000

const server = http.createServer((req, res) = > {
  res.statusCode = 200
  res.setHeader('Content-Type'.'text/plain')
  res.end('welcome to www.flydean.com\n')
})

server.listen(port, hostname, () = > {
  console.log(`please visit http://${hostname}:${port}/ `)})Copy the code

The HTTP service created above listens on port 3000. We create the HTTP service by using the createServer method.

This method takes a callback function with two parameters: REq (http.IncomingMessage object) and an RES (http. ServerResponse object).

In the above example, we set header and body values in Response and end the response with an end method.

Request the NodeJS service

Once an HTTP Web service is created, it is typically accessed and invoked from the Web browser side. However, we sometimes need to invoke the HTTP interface of a third-party application from the NodeJS back-end service. The following example will show how to invoke the HTTP service using NodeJS.

Let’s start with the simplest GET request:

const http = require('http')
const options = {
  hostname: 'www.flydean.com'.port: 80.path: '/'.method: 'GET'
}

const req = http.request(options, res= > {
  console.log(`status code: ${res.statusCode}`)

  res.on('data'.d= > {
    console.log(d);
  })
})

req.on('error'.error= > {
  console.error(error)
})

req.end()
Copy the code

The above code uses http.request to create a request and passes in our own options parameter.

We handle this through the res callback event.

Let’s look at a simple POST request:

const http = require('http')

const data = JSON.stringify({
  name: 'flydean'
})

const options = {
  hostname: 'www.flydean.com'.port: 80.path: '/'.method: 'POST'.headers: {
    'Content-Type': 'application/json'.'Content-Length': data.length
  }
}

const req = http.request(options, res= > {
  console.log(`status code: ${res.statusCode}`)

  res.on('data'.d= > {
    console.log(d);
  })
})

req.on('error'.error= > {
  console.error(error)
})

req.write(data)
req.end()
Copy the code

Post is similar to GET, but the method in Options is different. Put can have multiple request types, so we need to specify headers.

Similarly, PUT and DELETE can be called in the same way.

The third-party lib requests a POST

Using http.request directly from NodeJS is a bit complicated, so we need to build our own options. Using a third-party library such as Axios can make post requests much easier:

const axios = require('axios')

axios
  .post('http://www.flydean.com', {
    name: 'flydean'
  })
  .then(res= > {
    console.log(`status code: ${res.statusCode}`)
    console.log(res)
  })
  .catch(error= > {
    console.error(error)
  })
Copy the code

In the example above, we use axios’s POST request directly, seal the request result as a promise, and then and catch the corresponding data processing. Very convenient.

Gets the body of the HTTP request

In the above example, we output the body of the HTTP request by listening for the REQ’s data event:

  res.on('data'.d= > {
    console.log(d); })})Copy the code

The problem with this is that you don’t always get the full body of the HTTP request.

Because the ON Data event of the RES is fired when the server gets the HTTP request header, the body of the request may not have been transmitted yet, in other words, the Request in the request callback is a stream object.

We need to deal with:

const server = http.createServer((req, res) = > {
  let data = []
  req.on('data'.chunk= > {
    data.push(chunk)
  })
  req.on('end'.() = > {
    console.log(JSON.parse(data)); })})Copy the code

Each time the data event is triggered, we push the received value into an array. When all the values are received and the end event is triggered, the output will be unified.

This is obviously a bit of a hassle.

We introduce a simple method in the Express framework, using the body-parser module:

const bodyParser = require('body-parser')

app.use(
  bodyParser.urlencoded({
    extended: true
  })
)

app.use(bodyParser.json())

app.post('/'.(req, res) = > {
  console.log(req.body)
})
Copy the code

In the example above, body-Parser encapsulates the REQ, so we’ll just focus on the final result.

Express and use Express to build HTTP Web services

What is Express?

Express is a fast, open and minimalist Web development framework based on node. js platform. It provides a powerful set of features to help you create a variety of Web and mobile applications.

Rich HTTP shortcuts and arbitrary combinations of Connect middleware make it quick and easy to create robust, friendly apis.

Express does not secondary abstract the existing features of Node.js; we simply extend the basic functionality required for Web applications on top of it.

express helloworld

Let’s see how to build a HelloWorld using Express:

var express = require('express');
var app = express();
app.get('/'.function (req, res) {
  res.send('Hello World! ');
});
var server = app.listen(3000.function () {
  var host = server.address().address;
  var port = server.address().port;
  console.log('Example app listening at http://%s:%s', host, port);
});

Copy the code

Simply build an HTTP Web service using app.Listen.

Express route

With Web services, we need to handle different request paths and requests differently, which is where express routing comes in:

// A visit to the homepage returns "Hello World!" With the words
app.get('/'.function (req, res) {
  res.send('Hello World! '); });// The homepage accepts POST requests
app.post('/'.function (req, res) {
  res.send('Got a POST request'); });// / The user node accepts the PUT request
app.put('/user'.function (req, res) {
  res.send('Got a PUT request at /user'); });// / The user node accepts the DELETE request
app.delete('/user'.function (req, res) {
  res.send('Got a DELETE request at /user'); });Copy the code

More advanced, we can also do route matching in the request path:

// Match acD and ABcd
app.get('/ab? cd'.function(req, res) {
  res.send('ab? cd'); });// Matches abcd, abbcd, abbbcd, etc
app.get('/ab+cd'.function(req, res) {
  res.send('ab+cd');
});
// Matches abcd, abxcd, abRABDOMcd, and ab123cd
app.get('/ab*cd'.function(req, res) {
  res.send('ab*cd');
});
// Match/Abe and /abcde
app.get('/ab(cd)? e'.function(req, res) {
 res.send('ab(cd)? e'); });// Match any path that contains a:
app.get(/a/.function(req, res) {
  res.send('/a/');
});

Butterfly, Dragonfly, butterflyman, Dragonfly Man, etc
app.get(/.*fly$/.function(req, res) {
  res.send('/.*fly$/');
});

Copy the code

Express routing handle middleware

In some cases, a request may have more than one handler, and Express provides routing handles (middleware) that allow us to freely combine handlers.

Notice that in the route handle, we need to call the next method to trigger the next routing method.

var cb0 = function (req, res, next) {
  console.log('CB0'); next(); }var cb1 = function (req, res, next) {
  console.log('CB1'); next(); } app.get('/example/d', [cb0, cb1], function (req, res, next) {
  console.log('response will be sent by the next function ... ');
  next();
}, function (req, res) {
  res.send('Hello from D! ');
});
Copy the code

The above request will pass through cb0, cb1 and two custom functions, and finally end.

Express response method

Express provides a number of response method apis that make it easy for us to write code:

methods describe
res.download() Prompts you to download the file.
res.end() End the response processing process.
res.json() Send a response in JSON format.
res.jsonp() Send a JSONP-enabled JSON response.
res.redirect() Redirect the request.
res.render() Render the view template.
res.send() Send various types of responses.
res.sendFile Sends a file as an octet stream.
res.sendStatus() Sets the response status code and sends it as a string as part of the response body.

Static resources for Express

In express, you can use express.static to specify the path to a static resource:

app.use(express.static('public')); The files under the public directory are now accessible.http://localhost:3000/images/kitten.jpg
http://localhost:3000/css/style.css
http://localhost:3000/js/app.js
http://localhost:3000/images/bg.png
http://localhost:3000/hello.html
// Multiple static resource directories
app.use(express.static('public'));
app.use(express.static('files'));
// Static prefix
app.use('/static', express.static('public'));
http://localhost:3000/static/images/kitten.jpg
http://localhost:3000/static/css/style.css
Copy the code

Express uses a template engine

Web applications, of course, require HTML files, and multiple template languages are available in Express to make writing HTML pages easier. If you want to use a template engine. We can use the following steps:

  1. Set (‘views’, ‘./views’)

  2. Set (‘ View engine’, ‘Jade ‘)

  3. Create a Jade template file named index.jade in the views directory, with the following contents:

html head title! = title body h1! = messageCopy the code
  1. Configure the route rule on the NodeJS server
// Configure the route rule
app.get('/'.function (req, res) {
  res.render('index', { title: 'Hey'.message: 'Hello there! '});
});
Copy the code

conclusion

Nodejs and Express are very convenient HTTP Web services frameworks that I hope you enjoy.

Author: Flydean program stuff

Link to this article: www.flydean.com/nodejs-http…

Source: Flydean’s blog

Welcome to pay attention to my public number: “procedures those things” the most popular interpretation, the most profound dry goods, the most concise tutorial, many you do not know the small skills you find!