javascript 如何从 getInitialProps 中的 url 获取查询参数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48736902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do you get query params from the url in getInitialProps?
提问by cocoPuffs
I have a clean url that contains some query param like this.
我有一个干净的 url,其中包含一些这样的查询参数。
I'm trying to capture the query parameter 'id' on the client side like this.
我正在尝试像这样在客户端捕获查询参数“id”。
static async getInitialProps({req, query: { id }}) {
return {
postId: id
}
}
render() {
const props = {
data: {
'id': this.props.postId // this query param is undefined
}
}
return (
<Custom {...props}>A component</Custom>
)
}
My express endpoint looks like this.
我的快速端点看起来像这样。
app.post(
'/post/:id',
(req, res, next) => {
let data = req.body;
console.log(data);
res.send('Ok');
}
);
But my server side console output ends up like this.
但是我的服务器端控制台输出最终是这样的。
{ id: 'undefined' }
I've read the docs and the github issues but I can't seem to understand why this is happening.
我已经阅读了文档和 github 问题,但我似乎无法理解为什么会发生这种情况。
回答by saimeunt
Your frontend code is correct, fetching the post id from the query string is the way to go.
您的前端代码是正确的,从查询字符串中获取帖子 ID 是可行的方法。
However your backend code is incorrect, first you need to use a GET route to render a Next.js page, and you must extract the path params to craft the final query params as a combination from both the regular query params as well as those path params, this could look like this using express:
但是您的后端代码不正确,首先您需要使用 GET 路由来呈现 Next.js 页面,并且您必须提取路径参数来制作最终查询参数作为常规查询参数和那些路径的组合params,这可能看起来像这样使用 express:
const app = next({ dev: process.env.NODE_ENV === 'development' });
app.prepare().then(() => {
const server = express();
server.get('/post/:id', (req, res) => {
const queryParams = Object.assign({}, req.params, req.query);
// assuming /pages/posts is where your frontend code lives
app.render(req, res, '/posts', queryParams);
});
});
Check this Next.js example: https://github.com/zeit/next.js/tree/canary/examples/parameterized-routingfor more info.
查看 Next.js 示例:https: //github.com/zeit/next.js/tree/canary/examples/parameterized-routing了解更多信息。

