我有一个包含两个页面的Next.js应用程序。我的结构如下所示:
/pages
/index.js
/city.js
我创建了一个自定义服务器,这样,如果用户转到主页以外的其他位置,则应呈现city.js。例如,如果您转到myapp.com/phl,则该网址应保持为myapp.com/phl,但应呈现city.js。如果您访问myapp.com/stl,同样如此。
这是我的自定义服务器:
const express = require('express');
const next = require('next');
const url = require('url');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.get('*', (request, response) => {
return handler(request, response);
});
server.get('/:airportCode', (request, response) => {
console.log('hello from the server');
app.render( request, response, '/city', { ...request.query, ...request.params } );
});
server.listen(3000, error => {
if (error) throw error;
console.log('> Ready on http://localhost:3000');
});
})
.catch(exception => {
console.error(exception.stack);
process.exit(1);
});
当我访问主页时,它可以使页面显示得很好,但是当我访问https://myapp.com/phl时,我得到了404。我缺少什么吗?
答案 0 :(得分:1)
您需要使用星号页面处理程序来切换页面处理程序:
const express = require('express');
const next = require('next');
const url = require('url');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handler = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.get('/:airportCode', (request, response) => {
console.log('hello from the server');
app.render( request, response, '/city', { ...request.query, ...request.params } );
});
server.get('*', (request, response) => {
return handler(request, response);
});
server.listen(3000, error => {
if (error) throw error;
console.log('> Ready on http://localhost:3000');
});
})
.catch(exception => {
console.error(exception.stack);
process.exit(1);
});
星号的功能就像是先前功能未处理的任何路径的后备。