Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/github/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 如何在NodeJSRESTAPI中使参数可选_Node.js_Rest_Node Request - Fatal编程技术网

Node.js 如何在NodeJSRESTAPI中使参数可选

Node.js 如何在NodeJSRESTAPI中使参数可选,node.js,rest,node-request,Node.js,Rest,Node Request,我们需要公开REST端点。有三个参数,如何使这些可选。 要求是它应该与这些参数中的任何一个一起工作 e、 g.http://server:port/v1/api/test-api/userId/UnameName/userEmail app.get('v1/api/test-api/:userId/:userName/:userEmail', function(req, res){ }); 当我们通过传递所有三个参数进行调用时,它工作正常。但我们希望通过只传递userId或这三个参数中的任何

我们需要公开REST端点。有三个参数,如何使这些可选。 要求是它应该与这些参数中的任何一个一起工作

e、 g.
http://server:port/v1/api/test-api/userId/UnameName/userEmail

app.get('v1/api/test-api/:userId/:userName/:userEmail', function(req, res){

});
当我们通过传递所有三个参数进行调用时,它工作正常。但我们希望通过只传递userId或这三个参数中的任何一个来实现它。当我们传递更少的参数时,它的给定错误
无法获取/v1/api/test-api/test5/123


如何在公开端点时使参数可选?

您需要这样构造路由:

app.get('path/:required/:optional?*, ...)

更好的解决方案是使用GET参数,例如调用

http://server:port/v1/api/test-api?userId=123&userName=SomeKittens&userEmail=kittens%40example.com
然后,您可以定义您的路线,如:

app.get('v1/api/test-api', function(req, res){
  var userName = req.query.userName;
  var userEmail = req.query.userEmail;
  var userId = req.query.userId;

  // Do stuff
});

别忘了加入()

如果想让@thebiglebowsy的答案更清晰,你可以使用:

必需的->required1/required2/

可选->?可选/?可选2/

但是,我的建议是根据每个可能性生成一条路线:

v1/api/test-api/:userId/

v1/api/test-api/:userId/:userName

v1/api/test-api/:userId/:userName/:userEmail

app.get('v1/api/test-api/:userId/:userName/:userEmail', function(req, res){

});

我在使用可选路由时遇到了几个问题。另外,您可以检查输入请求参数中是否收到了内容,并相应地放入验证或捕获值

app.post('/v1/api/test-api', function(req, res) {
    var parameters = [];
    if(req.body.userName !== undefined) {
         //DO SOMEHTING
         parameters.push({username: req.body.userName});
    }
    if(req.body.userId !== undefined) {
        //DO SOMEHTING

       parameters.push({userId: req.body.userId});
   }
   if(req.body.userEmail !== undefined) {
      //DO SOMEHTING
      parameters.push({userEmail: req.body.userEmail});
   }

   res.json({receivedParameters: parameters});

});

此API正在访问的资源是什么?