路由是指应用程序的端点 (URIs) 如何响应客户请求。
路由方法
以下代码是为 GET 定义的路由和应用根部的 POST 方法的示例。
注意:使用post请求需要下载 body-parser
const express = require('express')
const app = express()
const port = 3000
// req.query 获取url参数
// req.params 动态路由参数
// req.body 获取post参数
//post 请求
const parser = require('body-parser')
app.use(parser.json())
app.post('/', (req, res) => {
// res.send('Hello World!')
console.log(req.body);
res.send(req.body)
})
//get请求
app.get("/",(req, res) => {
console.log(req.params);
console.log(req.query);
})
app.listen(port, () => {
console.log(`http://localhost:${port}`)
})
路线路径
此路由路径将匹配请求与根路。/
app.get('/', function (req, res) {
res.send('root')
})
此路由路径将匹配请求 。/about
app.get('/about', function (req, res) {
res.send('about')
})
此路由路径将匹配请求 。/random.text
app.get('/random.text', function (req, res) {
res.send('random.text')
})
以下是基于字符串模式的路线路径的一些示例。
这条路线路径将匹配和 。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
abRANDOMcd
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
dragonflyman
app.get(/.*fly$/, function (req, res) {
res.send('/.*fly$/')
})