Create a simple server using HTTP for Node

As we all know, using Node to create a simple local server can be created using the HTTP module createServer, for example:

//server.js

const http = require('http');

const server = http.createServer((request, response) => {
    response.writeHead(200, {'Content-Type': 'text/html'});
    response.end("This is a server by Node.js");
});

server.listen(1234);
Copy the code

This completes the creation of an HTTP server, starts with Nodeserver.js, and simply visits http://localhost:1234 to see the output: This is a server by Node.js

Express is a node-based framework that allows you to quickly build a server. For more information about Express, please visit www.expressjs.com.cn/

Create a local server using Express

The installation of the express

npm install express --save
Copy the code

Quick setup

//server.js
const express = require('express');
const app = express();
const port = 1234;

app.get('/', (req, res) => {
  res.send('Hello World!')
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
});
Copy the code

Start with Nodeserver.js, and simply visit http://localhost:1234 to see the output: Hello World!

Based on the routing

app.METHOD(PATH, HANDLER)

  • An example of App Express
  • METHOD Request METHOD
  • PATH Request PATH
  • HANDLER Callback function when path matches
app.get('/example', (req, res) => { res.send({ message: 'Hello World! '})})Copy the code
app.post('/user', (req, res) => {
  res.send({
    message: 'Got a POST request'
  })
})
Copy the code
app.put('/user', (req, res) => {
  res.send('Got a PUT request at /user')
})
Copy the code
app.delete('/user', (req, res) => {
  res.send('Got a DELETE request at /user')
})
Copy the code

You can pass multiple callbacks, but only when using the next argument:

app.get('/example', (req, res, next) => { console.log('the response will be sent by the next function ... ') next() }, (req, res) => { res.send('Hello from example! ')})Copy the code

For example, add more callbacks:

const cb0 = function (req, res, next) { console.log('CB0') next() } const cb1 = function (req, res, next) { console.log('CB1') next() } const cb2 = function (req, res) { res.send('Hello from C! ') } app.get('/example', [cb0, cb1, cb2])Copy the code

Even more amazing, you could write:

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

There is a special function: app.all(path,function)

app.all('/user',(req, res, next) => {
  res.send('Got a All request at /user'')
})
Copy the code

Unlike functions such as GET/POST, the app.all() function matches all HTTP requests, meaning it can filter requests from all paths. If you use all to define middleware, then all requests must pass through this middleware first

We use the all function to set the response header properties before the request, as shown below:

const express = require("express"); const app = express(); App. all("*", function(req, res, next) {// Set the response header attribute res.writeHead(200, {" content-type ": "text/ HTML; charset=utf-8" }); next(); }); App.get ("/", function(req, res) {res.send(" welcome to the home page! ); }); App.get ("/about", function(req, res) {res.send(" welcome to the about page! ); }); App. get("*", function(req, res) {res.send("404 - not found!" ); }); app.listen(1234);Copy the code

The “*” parameter in the above code indicates that it is valid for all paths. This method is particularly useful when dealing with a particular prefix path or any path

Express also provides a route() method that allows you to chain requests after creating a request path:

app.route('/book')
  .get(function (req, res) {
    res.send('Get a random book')
  })
  .post(function (req, res) {
    res.send('Add a book')
  })
Copy the code

The middleware

Middleware functions are functions that can access request objects (REq), response objects (RES), and the next function in the application’s request-response cycle. The next function is a function in the Express router that, when called, executes the middleware that takes over from the current middleware

The middleware features can perform the following tasks:

  • Execute any code.
  • Make changes to the request and response objects.
  • End the request-response cycle.
  • Call the next middleware in the stack.

We can use middleware functions with app.use()

Here’s an example:

const express = require('express'); const app = express(); const requestTime = function (req, res, next) { req.requestTime = Date.now(); next(); }; app.use(requestTime); app.get('/', function (req, res) { const responseText = 'Hello World! <br>'; responseText += '<small>Requested at: ' + req.requestTime + '</small>'; res.send(responseText); }); app.listen(3000);Copy the code

In the above example, the middleware function is used to modify the request object to set the requestTime attribute of the request object, so that when the GET request is called, the request object req has the requestTime attribute

Here are some practical middleware www.expressjs.com.cn/resources/m…

Express hosts static files

If you need to expose some static resources, such as CSS files, images, and HTML files, so that others can access these static resources, use:

express.static(root, [options])
Copy the code

This is a middleware function built into Express

For example, you can open images, CSS files, and JavaScript files in the public directory by using the following code:

app.use(express.static('public'));
Copy the code

Now you can access all files in the public directory:

http://localhost:1234/images/kitten.jpg

http://localhost:1234/css/style.css

http://localhost:1234/js/app.js

http://localhost:1234/images/bg.png

http://localhost:1234/hello.html

If you want to use multiple static resource directories, call the Express. static middleware function multiple times:

app.use(express.static('public'));
app.use(express.static('files'));
Copy the code

Create a virtual path to access files in the public directory. The virtual path itself does not exist in the system file directory:

app.use('/static', express.static('public'));
Copy the code

Now you can access files in the public directory with the /static prefix:

http://localhost:1234/static/images/kitten.jpg

http://localhost:1234/static/css/style.css

http://localhost:1234/static/js/app.js

http://localhost:1234/static/images/bg.png

http://localhost:1234/static/hello.html

Of course, the file path also needs to be handled according to the actual situation:

app.use('/static', express.static(path.join(__dirname, 'public')));
Copy the code

Use Express to handle cross-domain problems

This is the simplest implementation of handling cross-domains in Node:

const express = require('express'); const app = express(); const bodyParser = require('body-parser'); App. use(bodyParser.json({limit: '50MB'})); App. use(bodyParser.urlencoded({limit: '50MB ', parameterLimit: 100000, extended: true})); App. all("/*", function(req, res, next) {// Res. header(" access-Control-allow-origin ", "*"); res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'); res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS"); Res. The header (" X - Powered By ", '3.2.1); res.header("Content-Type", "application/json; charset=utf-8"); next(); // execute the next route}); App. get("/home", function(req, res) {res.send(" welcome to the home! ); }); App.listen (8787,()=>{console.log(' server enabled on port 8787 '); });Copy the code