从查询字符串中提取URL

时间:2017-01-27 09:16:11

标签: node.js url express query-string

考虑这样的网址:

http://some-site.com/something/ http://www.some-other-site.com

我正尝试使用以下方法从查询字符串(即第二个http://)向控制台登录粗体部分。

app.get("/something/:qstr",function(req,res){

    console.log(req.params.qstr);   
};

但是这只会在http: - >之前有效。一旦遇到//它就不再包含在req.params.qstr中我想知道如何获取整个URL字符串。我怎样才能做到这一点?

谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用正则表达式尝试此操作:

var app = require('express')();

app.get(/^\/something\/(.*)/, function (req, res) {

    console.log(req.params[0]);
    res.json({ok: true});

});

app.listen(3333, () => console.log('Listening on 3333'));

当你跑步时:

curl http://localhost:3333/something/http://www.some-other-site.com

服务器打印:

http://www.some-other-site.com

如你所愿。

res.json({ok: true});只会返回一些回复,因此curl不会永远挂起。