简体   繁体   English

使用自定义Express服务器时,端点返回404

[英]Endpoint returns 404 when using custom Express server

I have a Next.js app with two pages. 我有一个包含两个页面的Next.js应用程序。 My structure looks like the following: 我的结构如下所示:

/pages
    /index.js
    /city.js

I've created a custom server so that if the user goes to anything other than the home page it should render city.js. 我创建了一个自定义服务器,以便如果用户转到主页以外的其他任何内容,都应呈现city.js。 For example if you go to myapp.com/phl then the url should stay myapp.com/phl but it should render city.js. 例如,如果您转到myapp.com/phl,则该网址应保持为myapp.com/phl,但应呈现city.js。 The same applies if you go to myapp.com/stl. 如果您访问myapp.com/stl,同样适用。

Here's my custom server: 这是我的自定义服务器:

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);
    });

When I visit the home page it renders that page fine, but when I go to https://myapp.com/phl I get a 404. Am I missing something? 当我访问主页时,它可以很好地显示该页面,但是当我访问https://myapp.com/phl时,我得到一个404。我是否缺少某些东西?

You need to switch up your page handler with the asterisk page handler: 您需要使用星号页面处理程序来切换页面处理程序:

 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); }); 

The function of asterisk is like a fallback for any path that isn't handled by the previous function. 星号的功能就像是先前功能未处理的任何路径的后备。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM