Express framework

Web applications

Express is a minimum-sized flexible Node.js Web application development framework that provides a powerful set of capabilities for Web and mobile applications.

API

Create powerful apis quickly and easily using a variety of HTTP utilities and middleware of your choice.

performance

Express provides streamlined basic Web application functionality without hiding the Node.js functionality you know and love.

Express- Basic use of routing

NPM Install Express –save

Hello world

Create a new server.js file and type:

const express = require('express');
const app= express();

app.get('/', (req, res)=>{
    req.send('Hello world');
});
app.listen(8083, ()=>{
    console.log('Server is running at http://localhost:8083')})Copy the code

Then run: node server.js to open: http://localhost:8083/

Request and response

Express applications use callback arguments: Request and Response objects to process request and response data.

app.get('/'.function (request, response) {
   // --
})
Copy the code

Request and Response objects:

The Request object

The Request object represents an HTTP request and contains attributes such as the request query string, parameters, content, and HTTP header. Common attributes are:

Req. app: When callback is an external file, use req.app to access the express instance req.baseUrl: Obtain the URL path req.body/req.cookies: Stale: determines whether the request is still fresh. Req. hostname/req. IP: obtains the hostname and IP address req.originalUrl: Path: specifies the request path. Protocol: specifies the protocol type. Req. query: specifies the query parameter string of the URL. Getting the currently matched route req.subdomains: Getting the subdomain req.accepts() : Req.acceptscharsets/req.acceptsencodings/req.acceptslanguages: returns the first acceptable character encoding of the specified character set req.get() : Gets the specified HTTP request header req.is() : Determines the MIME Type of the request header content-type

The Response object

A Response object represents an HTTP response, which is the HTTP response data sent to the client when a request is received. Common attributes are:

Res.append () : appends the specified HTTP header res.set() after res.append() resets the previously set header res.cookie(name, value [, option]) : Setting cookies opition: Domain/Expires/httpOnly/maxAge/path/secure/signed res.clearcookie () : Res.get () : returns the specified HTTP header res.json() : sends the JSON response res.jsonp() : sends the jsonp response res.location() : Set the Location HTTP header for the response without setting the status code or close response res.redirect() : Set the Location HTTP header for the response, and set the status code 302 res.render(view,[locals],callback) : Render a view and pass the rendered string to the callback. If an error occurs during rendering, next(Err) will be called automatically. Callback will be passed a possible error and the rendered page so that it will not be output automatically. Res.send () : sends HTTP response res.sendFile(path [, options] [, fn]) : sends a file in the specified path – Content-type res.set() : Res.status () : sets the HTTP status code res.type() : sets the CONTent-type MIME type

Express – routing

We have seen the basic application of HTTP requests, and routing determines who (specifying scripts) responds to client requests. In HTTP requests, we can route out the request URL and GET/POST parameters.

Basic form of routing: app.method (PATH, HANDLER)

  1. appRepresents an instance of Express
  2. METHODIs the HTTP request method (get, pSOt..).
  3. PATHPath on the server
  4. HANDLERThe execution function after the request

The following example shows how to define a route:

// Get to /news page app.get('news', (req, res)=>{
    res.send('Hello news'); }); // Make a post request to the /about page app.post('about', (req, res)=>{
    res.send('Hello about'); }); // pair /list* matching /list+ any character app.get('/list*', (req, res)=>{
    res.send('Hello list pages');
})
Copy the code

Then run: node server.js to open: http://localhost:8083/

Express- Builds a static resource library

Express provides built-in middleware express.static to set static files such as images, CSS, JavaScript, etc.

You can use express.static middleware to set static file paths. For example, if you put images, CSS, JavaScript files in a public directory, you can write app.use(express.static(‘public’));

Now you can access all files in the public directory:

public/index.html
public/images
public/images/bg.jpeg
public/css
...
Copy the code

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

Express looks for files in static directories, so the name of the directory where the static files are stored does not appear in the URL. But you can add a route to static directories: app.use(‘/static’, express.static(path.join(__dirname, ‘public’))) sets /static to the route to /public. You can now access files in the public directory with the /static prefix.

http://localhost:8083/static/css
http://localhost:8083/static/css/index.css
http://localhost:8083/static/image
http://localhost:8083/static/images/bg.jpeg
http://localhost:8083/static/index.html
Copy the code

Use (‘/static’, express.static(path.join(__dirname, ‘public’)))) then run: node server.js to open: http://localhost:8083/static you can access all the files under the public, as shown in figure:

Express- EJS for template engines

EJS is a simple templating language that helps you generate HTML pages using ordinary JavaScript code.

Ejs: NPM install Ejs –save myejs.js:

const express= require('express'); const app = express(); // Set the directory for the template files, and create a new directory for viwes, app.set('views'.'./views'); // Register the template engine app.set('view engine'.'ejs'); // Use res.render() to render a view and send the rendered HTML string to the client; app.get('/'.function(req, res,) {
    res.render('index', { title: 'test'}); }); App.listen (8083, ()=>{console.log()'Server is running at http://localhost:8083')})Copy the code

Create a new index.ejs in the New Views directory:

 <h1><%= title %></h1>
Copy the code

Then run: node myejs.js and open: http://localhost:8083 to see:

Of course, you can return a JSON file to render the view: create a new data.json file in the same directory:

{
    "list": [{"name":"Xiao Ming" , "age":"6"."sex": "Male"},
    { "name":"Little red" , "age":"4" ,"sex": "Female"},
    { "name":"Little light" , "age":"5" ,"sex": "Male"}]."source":"Wonder Class Two"
}
Copy the code

Then change myejs.js:

const express= require('express');
const fs= require('fs'); const app = express(); // Set the directory for the template files, and create a new directory for viwes, app.set('views'.'./views'); // Register the template engine app.set('view engine'.'ejs'); // Use res.render() to render a view and send the rendered HTML string to the client; app.get('/'.function(req, res,) {
    getDataJson((dataJson)=>{
        console.log(dataJson);
        res.render('index', dataJson); })}); Const getDataJson=(callBack)=>{fs.readfile ()'./data.json', (err, data)=>{
        if(! err){let jsonData= JSON.parse(data);
            callBack(jsonData);
        }else{ throw err; }})} / / listen port 8083 app. Listen (8083, () = > {the console. The log ('Server is running at http://localhost:8083')})Copy the code

Then change index.ejs:

<h4><%=source %></h4>
<ul>
    <% for(var i=0; i<list.length; i++){ %>
        <li><%= list[i].name %> | <%= list[i].age %> | <%= list[i].sex %></li>
    <% } %>    
</ul>
Copy the code

Then run: then run: node myejs.js and open: http://localhost:8083

GitHub EJS template engine