我有 React+next 和 node js 项目,我想将该项目部署在一个端口中。为此,我为 js 创建了 ts 文件并运行了 . next 文件夹到后端。现在我的 API 和前端代码在同一个端口上工作。为此,我正在使用快递。但问题是它不需要任何 js 和 CSS 我的代码是:
app.use(express.static(path.join(__dirname, './server/.next/')));
app.get('*', (req, res) => {
res.sendFile(__dirname + '/server/.next/server/pages/index.html');
})
当我在 next 文件夹中打开 index.js 文件时,所有 css 和 js 路径都是以这种方式创建的:
<link rel="preload" href="/_next/static/css/33698e28f26f4e47.css"
如果手动我将删除 static/css/33698e28f26f4e47 前面的 _next,我的 css 正在工作。但由于 npm run build 命令创建的 index.js,我无法手动删除它
回答1
您应该更改 next.config 中的基本路径,因为我认为您的 node.js 根目录中没有“/_next/static/css/”路径。
module.exports = {
assetPrefix: 'assetPrefixPath',
...
publicRuntimeConfig: {
...
basePath: 'basePath',
...
},
}
回答2
它对我有用我在 index.js 中使用了这段代码:-
从“next”导入next;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
const port = process.env.PORT || 3000;
(async () => {
try {
await app.prepare();
const server = express();
server.all("*", (req: Request, res: Response) => {
return handle(req, res);
});
server.listen(port, (err?: any) => {
if (err) throw err;
console.log(`> Ready on localhost:${port} - env
${process.env.NODE_ENV}`);
});
} catch (e) {
console.error(e);
process.exit(1);
}
})();