This chapter introduces you to the introduction and basic knowledge of learning nodejs: express. So what is express? Express is a web development framework with minimal functions and is completely composed of routing and middleware: essentially, an express application is calling various middleware. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Initialization
Create a new directory myapp, project initialization
$ npm init
Install express
$ npm install express --save
Create a hello world instance
Enter the myapp directory and create a file named app.js
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); });
The above code starts a service and listens from port 3000 All incoming connection requests. It will return the "Hello World!" string to all (/) URLs or routes. All other paths return 404 Not Found.
Start through the following command line
$ node app.js
express generator
You can quickly create an application through the application generator tool express skeleton.
1. Install the following command
$ npm install express-generator -g
2. Create the myapp application in the current directory and run the following command
$ express myapp $ cd myapp $ npm install> set DEBUG=myapp & npm start
Applications created through the Express application generator generally have the following Directory structure:
├── app.js ├── bin │ └── www ├── package.json ├── public │ ├── images │ ├── javascripts │ └── stylesheets │ └── style.css ├── routes │ ├── index.js │ └── users.js └── views ├── error.jade ├── index.jade └── layout.jade 7 directories, 9 files
express routing
Routing is composed of a URI (or path) and a specific HTTP method ( GET, POST, etc.), involves how the application responds to the client's access to a website node. Each route can have one or more processor functions. When a route is matched, these functions/functions will be executed.
The definition of routing consists of the following structure: app.METHOD(PATH, HANDLER). Among them, app is an express instance; METHOD is one of the HTTP request methods; PATH is the path on the server side; HANDLER is the function that needs to be executed when the route is matched.
The following are some common routing codes:
var express = require('express'); var app = express(); // respond with "hello world" when a GET request is made to the homepage app.get('/', function(req, res) { res.send('hello world'); }); // POST method route app.post('/', function (req, res) { res.send('POST request to the homepage'); }); //app.all() 是一个特殊的路由方法,没有任何 HTTP 方法与其对应,它的作用是对于一个路径上的所有请求加载中间件。 app.all('/secret', function (req, res, next) { console.log('Accessing the secret section ...'); next(); // pass control to the next handler });
Example of routing path using string pattern: The characters ?, ,* and () are a subset of regular expressions, - and . String-based paths are interpreted literally.
// 匹配 acd 和 abcd app.get('/ab?cd', function(req, res) { res.send('ab?cd'); }); // 匹配 abcd、abbcd、abbbcd等 app.get('/ab+cd', function(req, res) { res.send('ab+cd'); }); // 匹配 abcd、abxcd、abRABDOMcd、ab123cd等 app.get('/ab*cd', function(req, res) { res.send('ab*cd'); }); // 匹配 /abe 和 /abcde app.get('/ab(cd)?e', function(req, res) { res.send('ab(cd)?e'); }); //使用正则表达式的路由路径示例: // 匹配任何路径中含有 a 的路径: app.get(/a/, function(req, res) { res.send('/a/'); }); // 匹配 butterfly、dragonfly,不匹配 butterflyman、dragonfly man等 app.get(/.*fly$/, function(req, res) { res.send('/.*fly$/'); });
Route handle
Can provide multiple callback functions for request processing, which behave like middleware. The only difference is that these callback functions may call the next('route') method and skip other route callback functions.
Route handles come in many forms, they can be a function, an array of functions, or a mixture of the two, as shown below:
//使用多个回调函数处理路由(记得指定 next 对象): app.get('/example/b', function (req, res, next) { console.log('response will be sent by the next function ...'); next(); }, function (req, res) { res.send('Hello from B!'); }); //使用回调函数数组处理路由: var cb0 = function (req, res, next) { console.log('CB0'); next(); } var cb1 = function (req, res, next) { console.log('CB1'); next(); } var cb2 = function (req, res) { res.send('Hello from C!'); } app.get('/example/c', [cb0, cb1, cb2]);
Response method
The methods of the response object (res) in the following table return a response to the client, terminating the request-response cycle. If no method is called in the route handle, requests from the client will hang.
Method Description:
res.download() prompts to download the file.
res.end() terminates the response processing process.
res.JSON() sends a response in JSON format.
res.jsonp() sends a response in JSON format that supports JSONP.
res.redirect() redirects the request.
res.render() renders the view template.
res.send() sends 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.
app.route()
You can use app.route() to create a chained route handle for the routing path. Since the path is specified in one place, doing so helps create modular routing and reduces code redundancy and typos.
app.route('/book') .get(function(req, res) { res.send('Get a random book'); }) .post(function(req, res) { res.send('Add a book'); }) .put(function(req, res) { res.send('Update the book'); });
express.Router
You can use the express.Router class to create modular, mountable route handles. A Router instance is a complete middleware and routing system, so it is often called a "mini-app".
Create a file named birds.js in the app directory with the following content:
var express = require('express'); var router = express.Router(); // 该路由使用的中间件 router.use( function timeLog(req, res, next) { console.log('Time: ', Date.now()); next(); }); // 定义网站主页的路由 router.get('/', function(req, res) { res.send('Birds home page'); }); // 定义 about 页面的路由 router.get('/about', function(req, res) { res.send('About birds'); }); module.exports = router;
Then load the routing module in the application:
var birds = require('./birds'); ... app.use('/birds', birds);
The application can process the messages sent from /birds and /birds/about requests, and calls the timeLog middleware specified for that route.
Use Express to host static files
You can easily host static files, such as images, CSS, and JavaScript files through Express's built-in express.static wait.
Pass the directory where the static resource files are located as a parameter to express.static middleware to provide access to static resource files. For example, assuming you place images, CSS, and JavaScript files in the public directory, you can:
app.use(express.static('public'));
Now, the files in the public directory are 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
If your static resources are stored in multiple directories, you can call express.static middleware multiple times:
app.use(express.static('public')); app.use(express.static('files'));
如果你希望所有通过 express.static 访问的文件都存放在一个“虚拟(virtual)”目录(即目录根本不存在)下面,可以通过为静态资源目录指定一个挂载路径的方式来实现,如下所示:
app.use('/static', express.static('public'));
现在,你就爱可以通过带有 “/static” 前缀的地址来访问 public 目录下面的文件了。
http://localhost:3000/static/images/kitten.jpg http://localhost:3000/static/css/style.css http://localhost:3000/static/js/app.js http://localhost:3000/static/images/bg.png http://localhost:3000/static/hello.html
常见问题
如何处理 404 ?
在 Express 中,404 并不是一个错误(error)。因此,错误处理器中间件并不捕获 404。这是因为 404 只是意味着某些功能没有实现。也就是说,Express 执行了所有中间件、路由之后还是没有获取到任何输出。你所需要做的就是在其所有他中间件的后面添加一个处理 404 的中间件。如下:
app.use(function(req, res, next) { res.status(404).send('Sorry cant find that!'); });
Express 支持哪些模板引擎?
Express 支持任何符合 (path, locals, callback) 接口规范的模板引擎。
如何渲染纯 HTML 文件?
不需要!无需通过 res.render() 渲染 HTML。你可以通过 res.sendFile() 直接对外输出 HTML 文件。如果你需要对外提供的资源文件很多,可以使用 express.static() 中间件。
The above is the detailed content of Learning nodejs: express entry and basics. For more information, please follow other related articles on the PHP Chinese website!