从Angular UI-Router中获取Express API中的URL参数 [英] Get URL param in Express API from Angular UI-Router
问题描述
在Angular(ui路由器)中更改状态时,我无法获取传递的URL的参数:
I can't get the param of the URL which I pass when changing the state in Angular (ui router):
.state('contact.detail', {
url: '/:contactId',
templateUrl: 'detail.html',
controller: 'DetailController'
})
在Express中,我定义了一个API,但是问题是从我从ui路由器传递的URL(上面)中获取了参数.
In Express I define an API, but the problem is in getting the param from the URL which I passed from ui router (above).
server.js
server.js
var express = require('express');
var mysql = require('mysql');
var url = require('url');
var app = express();
app.use('/', express.static('../app'));
app.use('/bower_components', express.static('../bower_components/'));
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.jsonParser = bodyParser.json();
app.urlencodedParser = bodyParser.urlencoded({ extended: true });
//mysql connection setup
var connection = mysql.createConnection({
host : "localhost",
port: "3306",
user : "root",
password : "",
database : "db",
multipleStatements: true
});
app.get('/:id', app.urlencodedParser, function(req,res){
var id = req.params.id;
console.log(id); // => :id instead of value
connection.query('SELECT * FROM contacts WHERE contactId = ?', [id], function (error, results) {
if(error) {
throw error;
}
else {
res.end(JSON.stringify(results));
}
});
});
server.listen(3000, function () {
'use strict';
});
在日志中,我得到的是":id ",而不是实际值,例如" 45 ".
In log I get ":id" instead of the real value, for example "45".
我可以手动访问API
I can access the API manually
请查看 plunker 以获得状态详细信息.
Please take a look at the plunker for states details.
推荐答案
由于您使用的是ui-router(或ngRoute),因此它是客户端路由,如果您要从服务器调用路由,则必须创建一个具有$ http服务(或$ resource)的http调用,例如:
Since u are using ui-router (or ngRoute) , it is client side routing , if you want to call a route from your server you have to make a http call , with $http service (or $resource) , like:
//this is a example not tested.
.controller('DetailController', function($scope, $stateParams,$http){
console.log('Passed parameter contact id is:', $stateParams.contactId);
$scope.selectedContactId = $stateParams.contactId;
$http.get("localhost:3000/"+$stateParams.contactId)
.success(function(data){
//console.log(data)
})
.error(function(error,status){
})
});
这篇关于从Angular UI-Router中获取Express API中的URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!