Get URL param in Express API from Angular UI-Route

2019-09-11 11:32发布

问题:

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'
})

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';
});

In log I get ":id" instead of the real value, for example "45".

I can access the API manually

Please take a look at the plunker for states details.

回答1:

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){

         })
    });