logo
⚙️ 后端框架

Express

Express Cheat Sheet - 快速参考指南,收录常用语法、命令与实践。

📂 分类 · 后端框架🧭 Markdown 速查🏷️ 2 个标签
#express#nodejs
向下滚动查看内容
返回全部 Cheat Sheets

Getting Started

Hello World
  • "Create project, add package.json configuration

    BASH
    滚动查看更多
    $ mkdir myapp # create directory
    $ cd myapp    # enter the directory
    $ npm init -y # Initialize a configuration
    
  • Install dependencies

    BASH
    滚动查看更多
    $ npm install express
    
  • Entry file index.js add code:

    JS
    滚动查看更多
    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

    BASH
    滚动查看更多
    $ node index.js
    

    {.marker-timeline}

express -h
BASH
滚动查看更多
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

BASH
滚动查看更多
$ express --view=pug myapp
# run the application
$ DEBUG=myapp:*npm start
express()
:-:-
express.json()#
express.raw()#
express.Router()#
express.static()#
express.text()#
express.urlencoded()#
Router
:-:-
router.all()#
router.METHOD()#
router.param()#
router.route()#
router.use()#
Application
JS
滚动查看更多
var express = require('express');
var app = express();

console.dir(app.locals.title);
//=> 'My App'
console.dir(app.locals.email);
//=> 'me@myapp.com'

Attribute

:-:-
app.localsLocal variables in the application #
app.mountpathPath pattern for mounting sub-apps #

Events

:-:-
mountThe child application is mounted on the parent application, and the event is triggered on the child application #

Method

:-:-
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()#
Request

Attribute

:-:-
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#

Method

:-:-
req.accepts()#
req.acceptsCharsets()#
req.acceptsEncodings()#
req.acceptsLanguages()#
req.get()Get HTTP request header fields #
req.is()#
req.param()#
req.range()#
Response
JS
滚动查看更多
app.get('/', function (req, res) {
	console.dir(res.headersSent); //false
	res.send('OK');
	console.dir(res.headersSent); //true
});

Attribute

:-:-
res.app#
res.headersSent#
res.locals#

Method

:-:-
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()#

Example

Router

Called for any request passed to this router

JS
滚动查看更多
router.use(function (req, res, next) {
	//.. some logic here .. like any other middleware
	next();
});

will handle any request ending in /events

JS
滚动查看更多
//depends on where the router "use()"
router.get('/events', (req, res, next) => {
	//..
});
Response

The res object represents the HTTP response sent by the Express application when it receives an HTTP request

JS
滚动查看更多
app.get('/user/:id', (req, res) => {
	res.send('user' + req.params.id);
});
Request

A req object represents an HTTP request and has properties for the request query string, parameters, body, HTTP headers, etc.

JS
滚动查看更多
app.get('/user/:id', (req, res) => {
	res.send('user' + req.params.id);
});
res. end()
JS
滚动查看更多
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([body])
JS
滚动查看更多
res.json(null);
res.json({ user: 'tobi' });
res.status(500).json({ error: 'message' });
app.all
JS
滚动查看更多
app.all('/secret', function (req, res, next) {
	console.log('access secret section...');
	next(); // Pass control to the next handler
});
app.delete
JS
滚动查看更多
app.delete('/', function (req, res) {
	res.send('DELETE request to homepage');
});
app.disable(name)
JS
滚动查看更多
app.disable('trust proxy');
app.get('trust proxy');
// => false
app.disabled(name)
JS
滚动查看更多
app.disabled('trust proxy');
// => true

app.enable('trust proxy');
app.disabled('trust proxy');
// => false
app.engine(ext, callback)
JS
滚动查看更多
var engines = require('consolidate');

app.engine('haml', engines.haml);
app.engine('html', engines.hogan);
app.listen([port[, host[, backlog]]][, callback])
JS
滚动查看更多
var express = require('express');

var app = express();
app.listen(3000);
Routing
JS
滚动查看更多
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');
});
JS
滚动查看更多
// 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');
});
Middleware
JS
滚动查看更多
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');
});
Using templates
JS
滚动查看更多
app.set('view engine', 'pug');

Create a Pug template file named index.pug in the views directory with the following content

PUG
滚动查看更多
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

JS
滚动查看更多
app.get('/', (req, res) => {
	res.render('index', {
		title: 'Hey',
		message: 'Hello there!'
	});
});

相关 Cheat Sheets

1v1免费职业咨询
logo

Follow Us

linkedinfacebooktwitterinstagramweiboyoutubebilibilitiktokxigua

We Accept

/image/layout/pay-paypal.png/image/layout/pay-visa.png/image/layout/pay-master-card.png/image/layout/pay-airwallex.png/image/layout/pay-alipay.png

地址

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 5000

Disclaimer

footer-disclaimerfooter-disclaimer

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