首页 > 解决方案 > AngularJS 路由到 Express 服务器的路径

问题描述

我是 AngularJS、Node 和 Express 的初学者。
我什至无法使用 $http.get 或 $http.post 获得最基本的路由。
我在网上找到的每个示例都忽略了文件名、Angular 控制器路径和服务器中的路由路径之间的关系。他们只显示代码而不显示路径和文件名。

这是我的 html 文件:“/programs/static/example.html”:

<!DOCTYPE html>
<html ng-app="exampleApp">
<head>

</head>
<body>
    <div ng-controller="exampleController">
        <input type="submit" value="Click me" ng-click="request()">
    </div> 
    <script src="http://code.angularjs.org/1.6.9/angular.min.js"></script>
    <script src="/js/example-controller.js"></script>
</body>
</html>

这是我的 Angular 控制器:“/programs/static/js/example-controller.js”

var exampleApp = angular.module('exampleApp', []);

exampleApp.controller('exampleController', function($scope) {

    $scope.request = function() {
        data="test";
        $http.post("/" , data);
    };

});

这是我的 NodeJS 服务器:“/programs/node-server.js”

var express = require("express");

var app = express();
app.use('/', express.static('./static'));

app.post('/example.html/', function(req, res){
    console.log("request received.");
});


app.listen(80);

问题是我的服务器的控制台没有显示“收到请求”。这是我构建的一个示例应用程序,只是为了将其发布到 Stack Overflow。在我的真实应用中,我尝试了尽可能多的不同路线。我可以让我的节点服务器中的 app.get() 使用简单的 URL(不是 $http 方法)工作。但从我的测试中很明显,我的 Angular 控制器没有发送任何请求,或者服务器没有接收到它们。

标签: angularjsnode.jsexpressroutes

解决方案


Your POST endpoint should not have a file extension in it's name. Any posts to "example.html" will try to return an actual html file named example.html if you have any such file name in your \static folder. Your API endpoints should have clear unique names, with no file extension:

app.post('/test', function(req, res){
  console.log("request received.");
});

When using $http.post and passing "/" as the parameter, the actual URL that is posted to will be relative to your current URL. You should always use an absolute URL when posting to a server (unless you know what you are doing). You should also implement the .then and .catch methods. These will help you debug the problem:

$http.post("http://localhost:8080/test", data).then(function(response) {
  console.log(response);  //this will log a success
}).catch(function(error) {
  console.log(error);  //this will log the error
});

You are also forgot to inject the $http provider in your controller:

exampleApp.controller('exampleController', function($scope, $http) {
  ...
});

推荐阅读