javascript - 使用 ExpressJS 和 AngularJS

标签 javascript angularjs node.js

我正在学习 NodeJS 和 Express。我使用 Node 和 Express 以及 2 个 Node 模块来获取客户端的 IP 地址。那部分工作正常。我在尝试使用 AngularJS (1.x) 在浏览器中使用 Angular 显示来自 Node 模块的地理位置数据时遇到问题。我做错了什么,因为我无法通过浏览器中的 Angular 获取要显示的地理数据。

 // get IP address
app.get('/ip', function (req, res, next) {
    //var ip = req.myCustomAttributeName;// use this for live
    //var ip = '207.97.227.239';/* use this for testing */
    console.log('requestIP is ' + ip);
    // geolocation
    geoip2.lookupSimple(ip, function(error, result) {
    if (error) {
        return res.status(400).json({error: 'Something happened'});
        }
        else if (result) {
        return res.send(result);
      }
    });
});

我相信 Express 可以正确提供我的静态文件

app.use('/assets', express.static(__dirname + '/public'));

我的/public 文件夹中的 index.html 提供 AngularJS 和我的 Angular 应用程序

    <html ng-app="UserLocation">
<title>The MEAN Stack</title>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>
</head>
<body ng-controller="MainController as vm">
    <h1 style="color:blue;">{{ vm.message }}</h1>
    <br>
    <h2 style="color:red;">{{ vm.location }}</h2>
    <script src="/assets/js/app.js"></script>
</body>
</html>

以及 Angular 应用

    angular.module('UserLocation', []);

angular.module('UserLocation')
    .controller('MainController', MainController);

MainController.$inject = ['$http'];

/*function ctrlFunc () {
    this.message = 'Hello World again';

};*/

function MainController($http) {
    var vm = this;
    vm.location = '';

    vm.message = 'Hello World';
    // user location
    //function getLocation () {
    vm.getLocation = function() {
        $http({
            method: 'GET',
            url: 'localhost:8000/ip'
        }).then(function (result) {
            console.log(result);
            return vm.location = result;
        });
      }; 
    };

IP 有效并显示在 '/ip' 处,但在 '/' 处我得到 Cannot GET/ 我对显示在“/”处的地理数据做错了什么

最佳答案

让您的客户端应用程序处理路由

// All other routes should redirect to the index.html
app.route('/*')
  .get((req, res) => {
    res.sendFile(path.resolve(__dirname + '/public/index.html'));
});

关于javascript - 使用 ExpressJS 和 AngularJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42043199/

相关文章:

javascript - 使用传单 slider 隐藏标记?

Javascript检查元组的第一个元素是否存在于元组数组中

javascript - 这是 Chrome 的错误吗?我该如何解决? : It skips some alert comments in the opener's Function

javascript - 使用 Tab 的 AngularJS 多页表单

node.js - Jest : Couldn't find preset "@babel/env" relative to directory

javascript - 在 asp.net-mvc 中使用 jquery 查找兄弟输入值

javascript - 上传文档时突出显示最新文件,并且滚动条应根据文档移动

javascript - ng-在提交时在 Angular 输入中无效

Javascript 代码未在 PUG/Jade 文件上运行

node.js - 如何根据日期过滤 Bunyan 日志?