如何从getInitialProps中的url获取查询参数?

coc*_*ffs 6 javascript express nextjs

我有一个干净的网址,其中包含一些查询参数.

HTTP://本地主机:3000 /后/: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>
  )
}
Run Code Online (Sandbox Code Playgroud)

我的快递端点看起来像这样.

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

但是我的服务器端控制台输出最终会像这样结束.

{ id: 'undefined' }
Run Code Online (Sandbox Code Playgroud)

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

sai*_*unt 3

您的前端代码是正确的,从查询字符串中获取帖子 ID 是正确的方法。

但是您的后端代码不正确,首先您需要使用 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);
  });
});
Run Code Online (Sandbox Code Playgroud)

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