Express路由req.params.username返回:username占位符问题求助
问题根源
- 前端
$http的params配置项作用是将参数拼接为URL的查询字符串(即?key=value格式),不会自动替换你写在URL路径里的:xxx占位符。所以你实际发起的请求路径是/movie/:title/:username?title=xxx&username=xxx,后端路由匹配到的路径参数自然就是占位符本身。 - 后端还有两个隐含问题:
- 对
req.oidc.user.email做了JSON.stringify处理,生成的字符串会自带双引号,和路径里拿到的无引号用户名永远匹配失败 - 删除数据时用了
req.query作为查询条件,你没有在查询串传参数的话永远匹配不到要删除的记录
- 对
修复方案
第一步 修复前端请求代码
手动拼接路径参数,不需要再传params配置:
$scope.del_movie = function(movie) { // 手动替换路径占位符,添加encodeURIComponent避免特殊字符导致路由匹配错误 const targetUrl = `/movie/${encodeURIComponent(movie.title)}/${encodeURIComponent(movie.username)}`; $http( { method: 'DELETE', url: targetUrl }).then(function successCallback(response) { console.log(response); return getData(); }, function errorCallback(response) { console.log('Error: ' + response); }); };
如果你确实需要用占位符替换的能力,可以改用AngularJS的$resource服务,它原生支持路径占位符替换逻辑。
第二步 修复后端逻辑问题
app.delete('/movie/:title/:username', requiresAuth(), function(req, res) { const paramsUsernameString = req.params.username; // 去掉JSON.stringify,避免生成带双引号的字符串导致匹配失败 const oidcEmailString = req.oidc.user.email; console.log("movie " + req.params.username); if(paramsUsernameString != oidcEmailString){ console.log("req.params.username " + paramsUsernameString + " req.oidc.user.username " + oidcEmailString); console.log("can't delete someone else's review!"); res.json({ message: "You can't delete someone else's review, as much as you may like to" }); } else{ // 用路径参数作为查询条件,不要用req.query Movie.findOneAndRemove({ title: req.params.title, username: req.params.username }, function(err, result) { if ( err ) throw err; res.json( { message: "req.params.username " + paramsUsernameString + " req.oidc.user.username " + oidcEmailString, movie: result }); }); } });
内容的提问来源于stack exchange,提问作者Casey
相关产品推荐
相关产品推荐

