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

时间:2022-11-25 13:59:52

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

我是Javascript和node.js的新手,我正在尝试创建一个REST API,而url将是这种形式。

  1. /user/{userId}/docs
  2. /用户/ {用户id} /文档

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

我试图获得{userId}的值,在/ user / 5 / docs的情况下将为5。

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

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

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

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

I am a traditional Java user and Jersey framework used to provide such a thing in Java.

我是一个传统的Java用户和Jersey框架,用于在Java中提供这样的东西。

Thanks, Tuco

谢谢,图科

3 个解决方案

#1


48  

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;
});

#2


1  

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');

#3


0  

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

#1


48  

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;
});

#2


1  

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');

#3


0  

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