实现get请求的路由
const express = require('express');const http = require('http');const app = express();app.set('port', 8080);app.get('/', (req, res) => { res.send('hello express');});app.get('/main', (req, res) => { const html = [ "Express
", "
Main
" ].join('\n'); res.send(html);});app.get('/users/:userId', (req, res) => { res.send('
Hello, User ' + req.params.userId + '
');});//catch route paramapp.param('userId', (req, res, next, val) => { console.log("request with userid: " + val); next();});app.get(/\/user\/(\d+)\/?(edit)?/, (req, res) => { var msg = ''; console.log(req.params[0]); if (req.params[1] === 'edit') { msg = "editing " + msg; } else { msg = "viewing " + msg; } res.send(msg);});http.createServer(app).listen(app.get('port'), () => { console.log('express server listening on port ' + app.get('port'));});
在浏览器中输入以下网址进行测试
127.0.0.1:8080127.0.0.1:8080/main127.0.0.1:8080/users/guest127.0.0.1:8080/users/visitor127.0.0.1:8080/user/a100 # CAT NOT GET127.0.0.1:8080/user/200127.0.0.1:8080/user/200/edit
Request对象和Response对象的一些属性
app.get('/', (req, res) => { const response = 'Simple Send ' + 'Hello Express
'; res.status(200); res.set({ 'Content-Type': 'text/html', 'Content-Length': response.length }); res.send(response); console.log('response finished ? :\t' + res.finished); console.log('headers sent:\t' + res.headerSent); console.log('URL:\t' + req.originalUrl); console.log('Protocol:\t' + req.protocol); console.log('IP:\t' + req.ip); console.log('Path:\t' + req.path); console.log('Host:\t' + req.hostname); console.log('Method:\t' + req.method); console.log('Fresh:\t' + req.fresh); console.log('Stale:\t' + req.stale); console.log('Secure:\t' + req.secure); console.log('Query:\t' + JSON.stringify(req.query)); console.log('Headers:\t' + JSON.stringify(req.headers, null, 2)); console.log('UTF-8:\t' + req.acceptsCharsets('utf8')); console.log('Connection:\t' + req.get('connection'));});
发送JSON响应
app.get('/json', (req, res) => { app.set('json spaces', 4); res.json({ name: "ming", age: 20, fruit: [ "apple", "banana", "orange" ], lang: { java: "good", cpp: "bad" } });});app.get('/error', (req, res) => { app.set('json spaces', 4); res.status(404).json({ code: 404, status: "false", message: "Not Found" });});
显示文件内容
app.get('/file', (req, res) => { res.sendFile('index.html', { root: './views/' }, (err) => { if (err) { console.log('error'); throw err; } else { console.log('success'); } });});
提供下载和重定向
app.get('/redirect', (req, res) => { res.redirect('/file');});app.get('/download', (req, res) => { res.download('./views/index.html', (err) => { if (err) { console.log('download error'); throw err; } else { console.log('download success'); } });});