【问题标题】:Static files inside `public` folder not being served (NextJS custom server using ExpressJS)`public` 文件夹中的静态文件未提供服务(使用 ExpressJS 的 NextJS 自定义服务器)
【发布时间】:2020-05-19 22:38:19
【问题描述】:

我正在开发NextJS 应用程序。我已经使用ExpressJS 制作了一个自定义服务器。问题是当我使用自定义服务器运行应用程序时,应用程序无法在 public 文件夹中找到静态文件。

注意:当我使用next dev 运行应用程序时,我没有任何问题

我的服务器

const express = require('express');
const next = require('next');
const path = require('path');

const port = parseInt(process.env.PORT, 10) || 3000;
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();

const prefix = (path = '') => `/:lang(en|tr)?`.concat(path);

app.prepare().then(() => {
    const server = express();

    server.get(prefix('/'), (req, res) => app.render(req, res, '/', req.query));
    server.get(prefix('/agency'), (req, res) => app.render(req, res, '/agency', req.query));
    server.get(prefix('/cases'), (req, res) => app.render(req, res, '/cases', req.query));
    server.get(prefix('/blog'), (req, res) => app.render(req, res, '/blog', req.query));
    server.get(prefix('/contact'), (req, res) => app.render(req, res, '/contact', req.query));

    server.get(prefix('/image.png'), (req, res) => app.render(req, res, '/public/images/avatar01.jpg', req.query));

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://localhost:${port}`);
    });
});

【问题讨论】:

    标签: express next.js


    【解决方案1】:

    这是因为您没有在没有匹配项时实现回退:

    server.all('*', async (req, res) => {
      return handle(req, res);
    }
    

    将为您处理所有其他路由(API 路由、公共/静态文件夹等)。

    【讨论】:

      猜你喜欢
      • 2020-02-21
      • 2012-11-20
      • 2014-10-29
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 2017-10-10
      相关资源
      最近更新 更多