博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Node.js Express 路由选择
阅读量:6076 次
发布时间:2019-06-20

本文共 3133 字,大约阅读时间需要 10 分钟。

hot3.png

实现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');        }    });});

 

转载于:https://my.oschina.net/nichijou/blog/748254

你可能感兴趣的文章
以太网到以太网的本地交换
查看>>
Windows Server 2012之活动目录域服务部署
查看>>
ORACLE Bug 4431215 引发的血案—处理篇
查看>>
js切割字符串问题
查看>>
微信语音遥控Windows Azure云虚拟机
查看>>
DNS主机记录也能用*
查看>>
监视DNS服务器工作是否正常
查看>>
理解并取证:动态路由协议RIP的工作原理
查看>>
你也可以拥有F5
查看>>
Windows Server 2012 Release Candidate (RC发行预览版) Datacenter抢鲜看
查看>>
疯狂ios讲义之疯狂连连看游戏简介
查看>>
shell编程培训之shell的工作原理
查看>>
Linux环境变量配置介绍及实战
查看>>
【VMCloud云平台】SCCM (九)添加报表点
查看>>
有关puppet agent端三种备份恢复方案探讨研究
查看>>
Linux下/etc/fstab文件详解
查看>>
统一沟通-技巧-13-Lync-Polycom RMX 1500-配置
查看>>
WindowsServer 2008 R2 Active Directory PowerShell
查看>>
大数据虚拟化零起点-3基础运维第二步-安装vSphere 5.1
查看>>
App-V5.0服务器部署
查看>>