AngularJS-对Localhost服务器的请求失败



我已经使用express.

制作了一个API终点。

现在,我试图从端口3010上运行的Localhost服务器中获取数据。

$scope.getBooks = function(){
$http.get('/api/books').then(function(resp){
  $scope.books = resp;
});
}

该功能运行良好,因为我可以测试jsonplaceholder.com。

我无法获取我的数据,我在端口3002上使用Gulp,我的服务器在端口3010中,他运行且工作良好,我可以使用Postman看到我的数据。

为什么我可以从Localhost服务器获取数据?

谢谢

此问题发生了,因为您要访问的API端点不会实现CORS。如果您在Chrome中运行代码并查看控制台,则会看到一个错误:

XMLHttpRequest cannot load .....

解决方案是更改API端点,以将访问控制 - 允许原始标头设置为通配符 *或将使用JavaScript代码的页面提供的域。

有关CORS的更多详细信息

To prevent websites from tampering with each other, web browsers implement a security measure known as the same-origin policy. The same-origin policy lets resources (such as JavaScript) interact with resources from the same domain, but not with resources from a different domain. This provides security for the user by preventing abuse, such as running a script that reads the password field on a secure website.

如果您的网站在端口3002上并且服务器在端口3010上,则必须指定整个服务器位置的URL

$scope.getBooks = function(){
    $http.get('http://localhost:3010/api/books').then(function(resp){
        $scope.books = resp;
    });
}

在AngularJS代码中指定整个URL,并在Express Backend中使用CORS中间件。

https://github.com/expressjs/cors

这是做前端(AngularJS(和后端开发在同一台计算机上的本地类别的不好方法。尝试适合前端存储库以由BE服务器托管并以以下方式使用:

如果您在本地进行FE开发,并且后端服务器也在本地托管。

使用以下行作为常见的baseurl

var baseUrl = "//" + window.location.host +'/'

这样做,您无需在对生产环境进行更改时需要更新。

 $scope.getBooks = function(){
    var _url = baseUrl +  '/api/books'
    $http.get(_url).then(function(resp){
      $scope.books = resp;
    });
}

上面的代码在同一服务器fe和be。

的情况下工作

如果您本地有不同的服务器,则需要在设置中进行更多工作:

您可以使用Express-HTTP-Proxy

var proxy = require('express-http-proxy');
app.use('/api/', proxy('http://localhost:3010'));

在Angular 4 版本的更高版本中,我们具有像初始配置一样的设置。

阅读文章:
https://jurist.com/blog/2016/11/configure-proxy-api-angular-cli/

您不能仅写/api/books。您需要指定在Localhost上运行的API的端口号。在您的情况下,本地主机:3010/api/books

最新更新