如何在Node.js中使用两个GET语句从GET URL中获取参数?

huangapple go评论50阅读模式
英文:

How to fetch parameters from GET URL in nodejs with two GET statements?

问题

以下是翻译好的部分:

在Node.js中:

这两个语句都需要用于获取所有记录和获取单个记录:

// 所有记录:
router.route('/').get((argReq, argRes) => { argRes.json(customerStruct.data); })

// 单个记录:
router.route('/id:').get((argReq, argRes) => { argRes.json({'id' : '5' })});

// 从ThunderClient:
http://localhost:7000/customerData/?id=0

以上返回所有值。似乎第二个GET请求没有被执行。

正确编写这些代码的方式是什么?

英文:

In Nodejs:

Both these statements need to be there for fetching all records and for fetching one record:

// All records:
router.route('/').get((argReq, argRes)=>{ argRes.json( customerStruct.data ); } )

// One record:
router.route('/id:').get((argReq, argRes) => { argRes.json({'id' : '5' })});

// From ThunderClient:
http://localhost:7000/customerData/?id=0

The above returns all values. It seems the second get request is not getting executed.

What is the way to correctly write all this?

答案1

得分: 0

有一个语法错误的问题:

要获取一个记录,: 需要位于变量的左侧。
/:id

英文:

There is a syntax error problem there:

For GETing one record, the : needs to be on the left side of the variable.
/:id.

答案2

得分: 0

如果你想要通过ID检索单个记录,你应该使用 argReq.params.id
你提供的已更正的代码片段应该类似于这样:

// 所有记录:
router.route('/').get((argReq, argRes) => { argRes.json(customerStruct.data); });

// 单个记录:
router.route('/:id').get((argReq, argRes) => {
    argRes.json({'id': customerStruct.data[argReq.params.id]});
});
// 假设 `customerStruct.data` 是所有记录的数组
英文:

If you're looking for how to retrieve a single record by id, you should use argReq.params.id.
corrected code snippet you provided should look something like this:

// All records:
router.route('/').get((argReq, argRes)=>{ argRes.json( customerStruct.data ); } 
) 
// One record:
router.route('/:id').get((argReq, argRes) => { 
    argRes.json({'id' : customerStruct.data[argRes.params.id] });
});

assuming customerStruct.data is an array of all of your records

huangapple
  • 本文由 发表于 2023年7月13日 16:46:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76677498.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定