Express Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。
"Create project, add package.json configuration
$ mkdir myapp # create directory
$ cd myapp # enter the directory
$ npm init -y # Initialize a configuration
Install dependencies
$ npm install express
Entry file index.js add code:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Listening port on ${port}`);
});
Run the application using the following command
$ node index.js
{.marker-timeline}
Usage: express [options] [dir]
Options:
-h, --help output usage information
--version output version number
-e, --ejs add ejs engine support
--hbs add hbs engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view No view engine generated
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (default jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (default css)
--git add .gitignore
-f, --force force non-empty directories
{.wrap-text}
Create a myapp project
$ express --view=pug myapp
# run the application
$ DEBUG=myapp:*npm start
var express = require('express');
var app = express();
console.dir(app.locals.title);
//=> 'My App'
console.dir(app.locals.email);
//=> 'me@myapp.com'
| :- | :- |
|---|---|
app.locals | Local variables in the application # |
app.mountpath | Path pattern for mounting sub-apps # |
| :- | :- |
|---|---|
mount | The child application is mounted on the parent application, and the event is triggered on the child application # |
| :- | :- |
|---|---|
app.all() | # |
app.delete() | # |
app.disable() | # |
app.disabled() | # |
app.enable() | # |
app.enabled() | # |
app.engine() | # |
app.get(name) | # |
app.get(path, callback) | # |
app.listen() | # |
app.METHOD() | # |
app.param() | # |
app.path() | # |
app.post() | # |
app.put() | # |
app.render() | # |
app.route() | # |
app.set() | # |
app.use() | # |
| :- | :- |
|---|---|
req.app | # |
req.baseUrl | # |
req.body | # |
req.cookies | # |
req.fresh | # |
req.hostname | # |
req.ip | # |
req.ips | # |
req.method | # |
req.originalUrl | # |
req.params | # |
req.path | # |
req.protocol | # |
req.query | # |
req.route | # |
req.secure | # |
req.signedCookies | # |
req.stale | # |
req.subdomains | # |
req.xhr | # |
| :- | :- |
|---|---|
req.accepts() | # |
req.acceptsCharsets() | # |
req.acceptsEncodings() | # |
req.acceptsLanguages() | # |
req.get() | Get HTTP request header fields # |
req.is() | # |
req.param() | # |
req.range() | # |
app.get('/', function (req, res) {
console.dir(res.headersSent); //false
res.send('OK');
console.dir(res.headersSent); //true
});
| :- | :- |
|---|---|
res.app | # |
res.headersSent | # |
res.locals | # |
| :- | :- |
|---|---|
res.append() | # |
res.attachment() | # |
res.cookie() | # |
res.clearCookie() | # |
res.download() | Prompt for files to download # |
res.end() | end the response process # |
res.format() | # |
res.get() | # |
res.json() | Send JSON response # |
res.jsonp() | Send a response with JSONP support # |
res.links() | # |
res.location() | # |
res.redirect() | Redirect request # |
res.render() | render view template # |
res.send() | Send various types of responses # |
res.sendFile() | Send a file as an octet stream # |
res.sendStatus() | # |
res.set() | # |
res.status() | # |
res.type() | # |
res.vary() | # |
Called for any request passed to this router
router.use(function (req, res, next) {
//.. some logic here .. like any other middleware
next();
});
will handle any request ending in /events
//depends on where the router "use()"
router.get('/events', (req, res, next) => {
//..
});
The res object represents the HTTP response sent by the Express application when it receives an HTTP request
app.get('/user/:id', (req, res) => {
res.send('user' + req.params.id);
});
A req object represents an HTTP request and has properties for the request query string, parameters, body, HTTP
headers, etc.
app.get('/user/:id', (req, res) => {
res.send('user' + req.params.id);
});
res.end();
res.status(404).end();
End the response process. This method actually comes from the Node core, specifically the response.end() method of
http.ServerResponse
res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });
app.all('/secret', function (req, res, next) {
console.log('access secret section...');
next(); // Pass control to the next handler
});
app.delete('/', function (req, res) {
res.send('DELETE request to homepage');
});
app.disable('trust proxy');
app.get('trust proxy');
// => false
app.disabled('trust proxy');
// => true
app.enable('trust proxy');
app.disabled('trust proxy');
// => false
var engines = require('consolidate');
app.engine('haml', engines.haml);
app.engine('html', engines.hogan);
var express = require('express');
var app = express();
app.listen(3000);
const express = require('express');
const app = express();
//Respond to "hello world" when making a GET request to the homepage
app.get('/', (req, res) => {
res.send('hello world');
});
// GET method routing
app.get('/', (req, res) => {
res.send('GET request to the homepage');
});
// POST method routing
app.post('/', (req, res) => {
res.send('POST request to the homepage');
});
function logOriginalUrl(req, res, next) {
console.log('ReqURL:', req.originalUrl);
next();
}
function logMethod(req, res, next) {
console.log('Request Type:', req.method);
next();
}
const log = [logOriginalUrl, logMethod];
app.get('/user/:id', log, (req, res, next) => {
res.send('User Info');
});
app.set('view engine', 'pug');
Create a Pug template file named index.pug in the views directory with the following content
html
the head
title= title
the body
h1=message
Create a route to render the index.pug file. If the view engine property is not set, the extension of the view file
must be specified
app.get('/', (req, res) => {
res.render('index', {
title: 'Hey',
message: 'Hello there!'
});
});
地址
Level 10b, 144 Edward Street, Brisbane CBD(Headquarter)Level 2, 171 La Trobe St, Melbourne VIC 3000四川省成都市武侯区桂溪街道天府大道中段500号D5东方希望天祥广场B座45A13号Business Hub, 155 Waymouth St, Adelaide SA 5000Disclaimer
JR Academy acknowledges Traditional Owners of Country throughout Australia and recognises the continuing connection to lands, waters and communities. We pay our respect to Aboriginal and Torres Strait Islander cultures; and to Elders past and present. Aboriginal and Torres Strait Islander peoples should be aware that this website may contain images or names of people who have since passed away.
匠人学院网站上的所有内容,包括课程材料、徽标和匠人学院网站上提供的信息,均受澳大利亚政府知识产权法的保护。严禁未经授权使用、销售、分发、复制或修改。违规行为可能会导致法律诉讼。通过访问我们的网站,您同意尊重我们的知识产权。 JR Academy Pty Ltd 保留所有权利,包括专利、商标和版权。任何侵权行为都将受到法律追究。查看用户协议
© 2017-2025 JR Academy Pty Ltd. All rights reserved.
ABN 26621887572