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

时间:2018-02-11 21:56:56

标签: javascript express nextjs

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

  

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问题,但我似乎无法理解为什么会这样。

1 个答案:

答案 0 :(得分:2)

您的前端代码是正确的,从查询字符串中提取帖子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了解更多信息。

相关问题