我希望我的下一个路由在从server.js(服务器端)运行以及在具有Link的链接端运行时,能够正常处理未找到的文件(实际上未找到路由)。我有一个解决方案,但是它体积很大,感觉好像我没有尽我所能。
我正在粘贴确实能够正确处理服务器和客户端的页面文件(pages / speakerdetail.js),但是在每个显示“未找到”的文件中必须具有自定义渲染方法似乎是错误的。
我也在仓库中以示例方式运行了
https://github.com/pkellner/next-routes-problem
import React, {Component} from 'react';
import {Link} from '../routes'
import Router from 'next/router'
class speakerdetail extends Component {
static async getInitialProps({req,res,query}) {
console.log("getInitialProps speakerdetail");
let statusCode = 200;
let slugSpeaker = '';
let ccYear = '';
if (query && query.slugSpeaker) {
console.log("query.slugSpeaker:" + query.slugSpeaker);
slugSpeaker = query.slugSpeaker;
}
if (query && query.ccYear) {
console.log("query.ccYear:" + query.ccYear);
ccYear = query.ccYear;
}
if (slugSpeaker != 'douglas-crockford-1124' || ccYear != '2018') {
if (req) {
console.log("getInitialProps - res.redirect cause server");
statusCode = 404;
res.statusCode = 404;
} else {
console.log("getInitialProps - router.push cause client")
Router.push('/error404');
}
}
return {
slugSpeaker,
ccYear,
statusCode
};
}
render() {
if (this.props.statusCode == 404) {
return (
<div>Not Found</div>
)
}
return (
<div>
<b>speakerdetail {this.props.ccYear} {this.props.slugSpeaker} {this.props.statusCode}</b>
<hr/>
<Link route='/' >
<a>home</a>
</Link>
</div>
);
}
}
speakerdetail.propTypes = {};
speakerdetail.defaultProps = {};
export default speakerdetail;
答案 0 :(得分:1)
与其手动检查传递给页面的每个参数,不如通过server.js
文件进行控制:
const next = require('next');
const routes = require('./routes');
const app = next({dev: process.env.NODE_ENV !== 'production'});
const handler = routes.getRequestHandler(app);
// With express
const express = require('express');
app.prepare().then(() => {
const srv = express();
srv.get('/:year/:slugSpeaker', (req, res) => {
const { year, slugSpeaker } = req.params;
return app.render(req, res, `/speakerdetail`, {
year,
slugSpeaker,
});
});
srv.use(handler).listen(3000)
});
然后,您可以尝试使用错误的数据打开网址,它将自动重定向到404页面。