如何将 URL 映射到 node.js 路由 [英] How to map URL to node.js route

查看:29
本文介绍了如何将 URL 映射到 node.js 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用带有 Angular 和 Node.js 的 ui-router 作为我的 UI 服务器,用于对另一台服务器的 API 调用.现在,我的浏览器 URL(基于下拉选择的动态)没有映射到服务器.

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.

例如,当我将用户输入发送到 Node 时,浏览器 URL 是/home?color=Red&&size=Large".当我将该 URL 复制并粘贴到另一个浏览器窗口中时,我希望颜色和大小下拉列表已经被选择为红色和大,并且基于显示的选择来自 API 调用的结果.我怎样才能做到这一点?

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?

我的 AngularJS 控制器代码:

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服务:

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

Angular 中的 ui-router:

ui-router in Angular:

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

在 Node.js 中,我的路线是这样的:

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

推荐答案

在你的代码中你写了查询参数但你需要阅读它们,试试这个:

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

这篇关于如何将 URL 映射到 node.js 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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