本期的演示存储库 https://github.com/hh54188/happy-server/tree/issue-demo
我尝试将Next.js与happy.js集成为插件。这是我的下一个.js插件项目文件夹主结构:
--plugins
|--app
|--pages
|--app
|--a.js
|--handlers
|--public
|--dist
|--index.js
|--next.config.js
这里是索引.js主要内容,大部分用于路由寄存器
const nextRenderService = next({
dir: path.join(__dirname)
});
module.exports = {
name: "AppService",
version: "0.0.1",
register: async function(server, options) {
await nextRenderService.prepare();
server.route({
method: "GET",
path: `/app/${assetPrefix}/_next/webpack-hmr`,
handler: nextHandlerWrapper(nextRenderService)
});
server.route({
method: "GET",
path: "/app/{param*}",
handler: defaultHandler(nextRenderService)
});
server.route({
method: "GET",
path: `/app/${assetPrefix}/_next/on-demand-entries-ping`,
handler: nextHandlerWrapper(nextRenderService)
});
server.route({
method: "GET",
path: `/app/${assetPrefix}/_next/-/page/{param*}`,
handler: {
directory: {
path: path.join(__dirname, pagesPath),
listing: true
}
}
});
server.route({
method: "GET",
path: `/app/${assetPrefix}/_next/{param*}`,
handler: {
directory: {
path: path.join(__dirname, distPath),
listing: true
}
}
});
}
};
但是,当我运行服务器并访问 http://127.0.0.1:4000/app/a 时,页面可能会成功,并且大多数脚本文件可以成功加载。但是_next/webpack-hmr
和_next/on-demand-entries-ping
请求状态是404
.我注意到 404 状态来自 Next.js,不高兴.js
那么我的代码有什么问题?我该如何解决这个问题?
将 nextjs 11> 12 升级后立即出现了此问题。
这对我有帮助:
npm install webpack-dev-server -g
来源: https://stackoverflow.com/a/31627310/
assetPrefix
配置仅用于使用 CDN,并且对 NextJs(文档(是全局的。您不想为其他内容设置它,例如修改 NextJs 路由器路径。如果不打算使用 CDN,请忽略此设置。
// in constants/index.js
const assetPrefix = process.env.NODE_ENV === "production"
? "https://cdn.mydomain.com"
: "";
您也不想列出所有 NextJs 内部路由并使用 NextJs 请求处理程序来处理所有调用:
// index.js
const next = require("next");
const path = require("path");
const nextRenderService = next({
dir: path.join(__dirname),
dev: process.env.NODE_ENV !== "production"
});
const { defaultHandler, nextHandlerWrapper } = require("./hanlders");
module.exports = {
name: "AppService",
version: "0.0.1",
register: async function(server, options) {
// https://github.com/zeit/next.js/blob/master/examples/custom-server-hapi/server.js
await nextRenderService.prepare();
// handle NextJs application requests
const handler = nextRenderService.getRequestHandler();
server.route({
method: "GET",
path: "/app/{p*}",
handler: async ({ raw, url }, h) => {
await handler(raw.req, raw.res, url);
return h.close;
}
});
// handle NextJs private routes
server.route({
method: "GET",
path: "/_next/{p*}" /* next specific routes */,
handler: nextHandlerWrapper(nextRenderService)
});
// Other routes
server.route({
method: "GET",
path: "/{p*}" /* catch all route */,
handler: defaultHandler(nextRenderService)
});
}
};