Express 总是在下一个函数后发送错误页
我坐的是快车4.16.3 首先,此代码工作正常:Express 总是在下一个函数后发送错误页,express,Express,我坐的是快车4.16.3 首先,此代码工作正常: const express = require('express') const router = express.Router() let app = express() router.use((req, res, next) => { console.log('hi, express') next() }) app.use(router) app.all('*', (req, res) => { r
const express = require('express')
const router = express.Router()
let app = express()
router.use((req, res, next) => {
console.log('hi, express')
next()
})
app.use(router)
app.all('*', (req, res) => {
res.send("hello, world")
})
app.listen(8075, function () {
console.log('listening localhost:8072')
})
但是当我试图在next()
中设置参数时:
响应始终是一个错误页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>hello, express</pre>
</body>
</html>
错误
你好,快车
我只是在下一个函数中添加了一个参数,但它似乎坏了
使用next()和params的正确方法是什么?我不知道在Express文档中的何处说明了这一点,但调用
next
时调用的不是另一个中间件函数,而是告诉Express框架调用下一个中间件函数。中间件函数具有传递给它的固定参数,因此您只能访问请求、响应和可能调用链中下一个中间件函数的函数。此函数可以选择的唯一参数是字符串'route'
为了将数据传递给下一个中间件函数,最好修改请求对象或响应对象
请参阅Express网站。在调用
next()
之前,使用req
对象附加所需数据不是更好的做法吗
这将使用请求
对象附加所需的数据,并将控件传递给下一个处理管道(app.all()
代码中的处理程序)
然后可以在所有可用的管线中使用该对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>hello, express</pre>
</body>
</html>
router.use((req, res, next) => {
req.data = { title: 'your sample data' };
next();
});
app.all('*', (req, res) => {
console.log(req.data);
});