最近在学习node.js,在使用express的时候出现了这个问题,记录一下解决方案。
出现情况的代码:
const express = require('express');
const app = express();
app.get('/', (req,resp)=>{
resp.send('index');
});
app.get('/about', (req,resp)=>{
resp.send('about');
});
app.get('/error', (req,resp)=>{
resp.send('访问错误');
});
app.listen(8080, ()=>{
console.log('listen on 8080');
})
启动运行后,如果是用get访问以上的路由,没有问题,
但我们如果用post方法或者输入其他的路径的话,就会出现 Cannot post
在页面上,这样就很不方便。
我想重定向到指定的一个页面,比如/error 页面,那么我们在 **最后一条路由 ** 加上下面这段代码即可:
app.all('*', function(req, resp) {
resp.redirect('/error');
});
最后的效果就是重定向到了 error
页面了
完整代码如下:
const express = require('express');
const app = express();
app.get('/', (req,resp)=>{
resp.send('index');
});
app.get('/about', (req,resp)=>{
resp.send('about');
});
app.get('/error', (req,resp)=>{
resp.send('访问错误');
});
//304重定向到错误页
app.all('*', function(req, resp) {
resp.redirect('/error');
});
app.listen(8080, ()=>{
console.log('listen on 8080');
})
此外,如果您不想未定义的post方法执行重定向,可以把上述解决方案的代码改为
app.get('*', function(req, resp) {
resp.redirect('/error');
});
这样的话,您将把所有除了已定义的路由的路径重定向到错误页了。