Javascript 如何在使用 node.js 时从 URL 获取 Id

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12160668/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:16:08  来源:igfitidea点击:

how to get the Id from the URL while using node.js

javascriptnode.jsexpress

提问by Tuco

I am quite new to Javascriptand node.jsand I'm trying to create a REST API, and the urls will be of the form.

我是很新的Javascript,并node.js和我试图创建一个REST API和网址将被形式。

  1. /user/{userId}/docs
  1. /user/{userId}/docs

I am trying to get the value of {userId}, which in the case of /user/5/docswill be 5.

我想获得的价值{userId},这在的情况下/user/5/docs5

I could try to pass this as a request parameter(in the querystring or in the body, depending on the GETor POSTmethod), but the url looks more intuitive when it is formed this will. Plus there are many more urls which are like these.

我可以尝试将其作为请求参数传递(在查询字符串中或在正文中,具体取决于GETPOST方法),但是 url 在形成时看起来更直观。此外,还有更多类似的网址。

I am wondering if there are any node modules like express which provide for this.

我想知道是否有像 express 这样的节点模块提供了这一点。

I am a traditional Javauser and Jerseyframework used to provide such a thing in Java.

我是一个传统的Java用户和Jersey框架,用于在Java.

Thanks, Tuco

谢谢,图科

回答by josh3736

Spend some time with the documentation. Express uses the :to denote a variable in a route:

花一些时间阅读文档。Express 使用:来表示路由中的变量:

app.get('/user/:id/docs', function(req, res) {
    var id = req.params.id;
});

回答by Saif Adnan

Write the following in the server script:

在服务器脚本中写入以下内容:

var http = require('http');
var server = http.createServer(function (request, response) {
    var url = request.url; //this will be /user/5/docs
    url.id = url.split("/")[2]; // this will be 5
    response.writeHead(200, {'Content-Type' : 'text/html'});
    response.end("Id is = " + url.id);
});
server.listen(8000, '127.0.0.1');

回答by Pradeep Banavara

var pathName = url.parse(request.url).pathname;
var id = pathName.split("=");
var userId = id[1];