How to map URL to node.js route

前提是你 提交于 2019-12-12 02:53:27

问题


I am using ui-router with Angular and Node.js as my UI server for API calls to another server. Right now, my browser URL (dynamic based on dropdown selections) does not map to the server.

For example, the browser URL is "/home?color=Red&&size=Large" when I send the user inputs to Node. When I copy and paste that URL in another browser window, I want the color and size dropdowns to already be selected as Red and Large, and results from API call based on the selections displayed. How can I accomplish this?

My AngularJS controller code:

$scope.getResults = function() {

    $location.search('color', $scope.myColor);
    $location.search('size', $scope.mySize);

    server.getResults($scope.myColor, $scope.mySize)
    .success(function(data) {
        results = data;
    });
};

AngularJS service for the above function:

app.factory('server', ['$http', function($http){
    return { 
        getResults : function(color, size) {
            var req = {};
            req.color = color;
            req.size = size;

            return $http({
                method: 'GET', 
                url: 'results',
                params : req
            });
        }
    }
}]);

ui-router in Angular:

$stateProvider.state('home', {
    url: '/home',
    templateUrl: '/home.html',
    controller: 'MainCtrl',
    reloadOnSearch: false
})

In Node.js, I have my route like this:

app.get("/results", function (req, res) {

    var api = 'some api call/' + req.query.color + '/' + req.query.size;

    request(api, function (error, response, api) {

        if (!error && response.statusCode == 200) {
            res.json({
                Response: api
            });
        }
    });
});

回答1:


In your code you wrote query parameters but you need to read them, try this:

$scope.getResults = function() {

  $scope.myColor = $location.search().color;
  $scope.mySize = $location.search().size;

  server.getResults($scope.myColor, $scope.mySize)
  .success(function(data) {
    results = data;
  });
};


来源:https://stackoverflow.com/questions/36670613/how-to-map-url-to-node-js-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!