【问题标题】:writing node.js get handler with parameters?用参数编写 node.js 获取处理程序?
【发布时间】:2014-01-07 19:00:39
【问题描述】:

如何使用 node.js 为以下 URL 编写获取处理程序?

http://localhost:3000/auth?code=xxxxxxx

以下代码无效

app.get('/auth', function (req,res) {

}); 

【问题讨论】:

    标签: node.js web-applications express


    【解决方案1】:

    它不起作用,因为它什么也没做。您需要发送回复:

    app.get('/auth', function (req,res) {
        res.send('Hi it worked. Code: ' + req.query.code);
    });
    

    另一种方法是这样的:

    app.get('/auth/:code', function (req,res) {
        res.send('Hi it worked. Code: ' + req.params.code);
    });
    

    URL 就是http://localhost:3000/auth/xxxxxxx

    【讨论】:

      【解决方案2】:

      请注意,某些客户端应该接受某种响应类型。 例如,您应该发送一个 JSON 对象作为响应。

      因此,与其只响应一个字符串,不如将一个 JSON 对象发送为:

      app.get('/auth', function (req,res) {
          res.send({ 'response' : 'Hi it worked.', 'code': req.query.code });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-13
        • 2014-08-03
        • 2012-01-16
        • 2013-11-11
        • 1970-01-01
        • 2017-08-02
        相关资源
        最近更新 更多