【问题标题】:How do you get query params from the url in getInitialProps?如何从 getInitialProps 中的 url 获取查询参数?
【发布时间】:2018-07-22 01:23:28
【问题描述】:

我有一个干净的 url,其中包含一些像这样的查询参数。

http://localhost:3000/post/:id

我正在尝试像这样在客户端捕获查询参数“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>
  )
}

我的快速端点看起来像这样。

app.post(
    '/post/:id',
    (req, res, next) => {
        let data = req.body;
        console.log(data);
        res.send('Ok');
    }
);

但我的服务器端控制台输出最终是这样的。

{ id: 'undefined' }

我已阅读文档和 github 问题,但我似乎无法理解为什么会发生这种情况。

【问题讨论】:

  • 你检查location.pathname了吗?
  • 是的,只是路径在那里 /post/B1L8VE0UF
  • 我想我可以直接在里面插入 location.pathname 而不是使用查询。
  • 我认为您需要根据执行环境同时使用两者。

标签: javascript express nextjs


【解决方案1】:

你的前端代码是正确的,从查询字符串中获取帖子 ID 是要走的路。

但是您的后端代码不正确,首先您需要使用 GET 路由来呈现 Next.js 页面,并且您必须提取路径参数以将最终查询参数作为常规查询参数的组合以及作为那些路径参数,使用 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);
  });
});

查看此 Next.js 示例:https://github.com/zeit/next.js/tree/canary/examples/parameterized-routing 了解更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 2023-02-21
    • 2018-05-07
    • 2016-06-11
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多