Home > Web Front-end > JS Tutorial > Nodejs express usage tutorial (with code)

Nodejs express usage tutorial (with code)

PHPz
Release: 2018-10-13 16:12:55
Original
1323 people have browsed it

Express is a simple and flexible node.js web application development framework. It provides a series of powerful features to help you create various web and mobile device applications.

1.express organizational structure

app demo

|---node_modules------for Install local modules.
|---public------------ is used to store files that users can download, such as pictures, scripts, style sheets, etc.
|---routes------------ is used to store routing files.
|---views------------- Used to store templates for web pages.
|---app.js------------The startup script of the application.
|---package.json------Project configuration file.

2.. Create express server

//app.js文件
var express = require('express');
var app = express();
//指定更目录显示的内容
app.get('/', function(req, res){
 res.send('Hello World');
});
//指定监听端口
var server = app.listen(3000, function() {
  console.log('Listening on port %d', server.address().port);
});
Copy after login

Run nodejs application

/>node app.js

3. Middleware

Middleware is a function that handles HTTP requests.
When an HTTP request enters the server, the server instance will call the first middleware. After completion, it will decide whether to call the next middleware according to the settings.

The parameters of the middleware are:

. When there are four - the first is error handling, the second is client request, the third is server response respond, and the fourth is next middleware. Such as function(error, request, response, next){}
. Three times---the first client requests request, the second is server response respond, and the third is next middleware. Such as function(request, response, next){ }
. When there are two---the first client requests request, and the second responds to the server respondfunction. Such as function(request, response){}

4. Use middleware use

use is express’s method of calling middleware, which returns a function.

app.use(function(request, response) {
 response.writeHead(200, { "Content-Type": "text/plain" });
 response.end("Hello world!\n");
});
Copy after login

5. Error content display

app.use(express.bodyParser());//使用body参数
app.use(express.methodOverride());//使用函数覆盖
app.use(app.router);//使用路由
app.use(function(err, req, res, next){
 console.error(err.stack);
 res.send(500, 'Something broke!');
});//错误内容显示
Copy after login

6. Routing

There are many ways to route express. Here are some commonly used examples:

.app.use('/', middleware);//When getting/posting, the processing of path /
.app.get("/", middleware);//When getting in http, the processing of path/
.app.post("/", middleware);//When post in http, the processing of path/ / Processing
.app.put("/", middleware);//When putting in http, processing of path/
.app.delete("/", middleware);//Delete in http When processing the path/

.: Capture path content

8. Set environment variables set
app.get("*", function(request, response) {
 response.end("404!");
});//所有路径都返回404
Copy after login

set is used to specify the value of a variable.

app.set("view engine", "ejs");//Use ejs as a template
app.get("/hello/:who", function(req, res) {
 res.end("Hello, " + req.params.who + ".");
});//如"/hello/alice”网址,网址中的alice将被捕获,作为req.params.who属性的值
Copy after login

9. response object method.Redirect redirect


response.redirect("/hello/anime");//Redirect to /hello/anime

.Send file sendFile response.sendFile("/path/to/anime.mp4");

. Render the web page template render, that is, load the transformed content into the web page.

response.render("index", { message: "Hello World" });//Pass the message variable into the index template, with the value "Hello World" rendered into an HTML web page

10. requst object method


. Get the customer ip address: request.ip

. Get the uploaded files: request.files

11. Startup script package.json

package.json is used to specify app information, nodejs version number and dependencies of other components

12.app entrance app.js

app.js mainly includes http creation, basic routing, and listening port number

{
  "name": "demo",
  "description": "My First Express App",
  "version": "0.0.1",
  "dependencies": {
   "express": "3.x"
  }
}
Copy after login
13. Dynamic web page template views

views folder is used to store all web page templates.

14. Specify the static web page directory

//app.js
app.use(express.static('public'));/ /Specify the static web page directory. When the browser sends a request for a non-HTML file, the server will go to the public directory to look for the file

For example:, the server will go to the public/bootstrap/css/ directory to look for bootstrap.css File

Okay, this tutorial will be introduced to you here. We will continue to update you in the future. Thank you for your continued support of the PHP Chinese website.

【Recommended related tutorials】

1. JavaScript video tutorial
2. JavaScript online manual
3. bootstrap tutorial

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template