【发布时间】:2020-03-11 20:15:41
【问题描述】:
我在使用 nextjs 时遇到了问题,但没有一个解决方案能帮到我!!!我,我试图在我的 SSR 项目中使用动态路由,在 localhost 中一切正常,但是当我尝试将其上传到服务器或我的 IIS 问题显示在 :问题在于,在第一次从服务器渲染时一切正常,刷新页面后,我丢失了查询字符串并且发生了未定义的错误。这是我的代码:
Server.js:
const express = require("express");
const next = require("next");
const port = process.env.PORT || 3003;
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare().then(() => {
const server = express();
server.get("/", (req, res) => {
return app.render(req, res, "/index");
});
server.get("/test?org&des&roomRules&departing&returning", (req, res) => {
return app.render(req, res, "/test" , {
org: req.query.org ,
des: req.query.des,
roomRules:req.query.roomRules,
departing: req.query.departing,
returning: req.query.returning,
});
});
server.get("*", (req, res) => {
return handle(req, res);
});
server.listen(port, err => {
if (err) throw err;
console.log(`READY ON http://localhost:${port}`);
});
});
父组件:
const RoundButton = props => {
const { searchParams , name} = props;
const URL2 = `/test?org=${searchParams.org}&des=${searchParams.des}&roomRules=${searchParams.roomRules}&departing=${searchParams.orgDate}&returning=${searchParams.desDate}`;
return (
<Link href={URL2} as={URL2}>
Test
</Link>
);
};
测试组件:
function Test(props) {
return (
<div>
<h1>Test</h1>
<h2>roomrules :{props.queryStrings}</h2>
</div>
)
}
Test.getInitialProps = ({query}) => {
const queryStrings = query;
return {
queryStrings: queryStrings
};
};
export default Test
如你所见,我使用了 getInitialProps,它只适用于第一次渲染。
最后是我在 package.json 中的脚本:
"scripts": {
"dev": "node server.js",
"build": "next build && next export",
"start": " node server.js"
},
要发布,我在 cmd 中编写“npm run build”。有什么解决办法吗?
【问题讨论】:
-
您找到解决方案了吗?
标签: node.js reactjs server-side-rendering