从 Angular UI-Router 获取 Express API 中的 URL 参数 [英] Get URL param in Express API from Angular UI-Router

查看:19
本文介绍了从 Angular UI-Router 获取 Express API 中的 URL 参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法获取在 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

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 调用,带有 $http 服务(或 $resource),例如:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆