如何从快递,帕拉姆和查询URL获得ID似乎并没有工作
我有一个url,我想获得身份证,但没有任何工作req.params或req.query
app.get('/test/:uid', function testfn(req, res, next) { debug('uid', req.params.uid); // gives :uid debug('uid', req.query.uid); // gives undefined });
我正在做一个像这样的ajax调用
$(document).on('click', 'a.testlink', function(e) { $.ajax({ type: "GET", url: '/test/:uid', success: function(var) { console.log('success'); }, error: function() { alert('Error occured'); } }); return false; });
我在用着
app.use(express.json()); app.use(express.urlencoded());
而不是身体分析器
你的代码是按预期工作的: ajax
调用指定url: '/test/:uid'
这是什么把:uid
在req.params.uid
。
尝试发送别的东西: url: '/test/123'
和req.params.uid
将包含123
这是一个可以工作的例子。 我将从一开始就一步一步的说明:
express myproject cd myproject npm install
打开app.js并在文件的下面添加 – 也许在app.get('/test/:uid',test);
var test = function(req,res,next) { // do whatever logic is needed res.end('Displaying information for uid ' + req.params.uid); } app.get('/test/:uid',test);
现在,打开一个新的terminal,确保你在myproject目录下,input:
node app.js
现在你可以访问本地机器上的http://localhost:3000/test/45
,你应该看到:
Displaying information for uid 45
如果您不是从本地机器访问,请确保更改上面的url以匹配您的节点应用程序运行的任何服务器。
另外,这只是一个简单的例子。 你可能会更好地组织一切,把路由放在一个类似于路由目录示例设置的文件中,在一个快速应用的新安装中。 你可以在网上find更详细的例子,比如这个和这个 。 另外,在Node中,我所看到的组织/重用代码的最好的解释之一就是NodeJS in Action一书。