问题描述
我正在localhost:3000/#!/上运行我的应用程序,并试图获取与Express一起使用的URL参数,但是没有运气.我创建了一个包含以下内容的新服务器路由文件:
I'm running my app on localhost:3000/#!/, and trying to get URL parameters for use with Express, with no luck. I've created a new server routing file that contains the following:
admin.server.routes.js
'use strict';
module.exports = function(app) {
// Admin Routes
var admin = require('../../app/controllers/admin.server.controller');
// Both of these routes work fine.
app.route('/admin/test').
get(admin.populate).
put(admin.update);
// First attempt, didn't work.
app.route('/admin/test').get(admin.doSomething);
// Second attempt, didn't work.
app.param('foo', admin.doSomething);
// Third attempt, didn't work.
app.param('foo', function(req, res) {
console.log('Found foo!');
return res.status(400).send();
});
};
在我的管理页面上,我的admin.client.controller.js在加载时发送一个$ http.get请求以填充数据.我有一个带有按钮的表单,该表单发送$ http.put请求以更新填充的值.这两个请求都可以正常工作.
On my admin page, my admin.client.controller.js sends an $http.get request on loading to populate the data. I have a form with a button the sends an $http.put request to update the populated values. Both of these requests work fine.
问题是当我尝试使用带有foo参数的URL访问我的应用程序时,例如:http://localhost:3000/#!/admin/test?foo=bar
.我已经在代码中尝试了上面提到的三种尝试中的每一种(注释掉其他尝试,以便可以一一尝试),但是似乎无法获取该变量.
The problem is when I try to visit my app using a URL with the foo parameter, like so: http://localhost:3000/#!/admin/test?foo=bar
. I've tried each of the three attempts noted above in my code (commenting out the others out so I could try them one by one), but cannot seem to get the variable.
在我的admin.server.controller文件中,除了填充和更新功能之外,我还简单地拥有以下代码:
In my admin.server.controller file, in addition to the populate and update functions, I simply have this code:
admin.server.controller
exports.doSomething = function(req, res) {
console.log('Server - found foo!');
};
我实际上没有使用任何这些努力就可以证明我已经成功地夺取"了foo供服务器端使用.我想念什么?
Using none of these efforts have I actually been able to demonstrate that I've successfully "grabbed" foo for server-side use. What am I missing?
推荐答案
在您的
http://localhost:3000/#!/admin/test?foo=bar
所有hashbang网址均由angularjs处理,因此该/admin/test?foo=bar
不会被视为请求.要在请求中添加查询字符串,可以在angularjs资源中执行以下操作:
all hashbang urls are handled by angularjs, this /admin/test?foo=bar
wouldn't be considered as a request. To add a query string in your request, you can do it like this in angularjs resource:
function ($resource) {
$resource('/admin/test').query({foo: 'bar'});
}
这将表示为此http://localhost:3000/admin/test?foo=bar
您的问题主要取决于您如何在客户端发送请求.
Your issue relies mostly on how you send your request on your client-side.
顺便说一句,在快递路线中,您可以这样获得foo值:
By the way, in your express routes you can get the foo value like this: Pre-routing with querystrings with Express in Node JS
如果要获取查询字符串并在请求中使用它,请参考以下内容:
If you wanted to get the query string and use it in your request, refer to this: How can I get query string values in JavaScript?
这篇关于MEANJS获取URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!