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

时间:2018-03-31 20:07:00

标签: angularjs http

我使用快递做了一个api终点。

现在我试图从我的本地主机服务器上获取在端口3010上运行的数据。

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

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

我无法获取我的数据,我在端口3002上使用gulp并且我的服务器在端口3010中,他正在运行且工作正常,我可以使用邮递员查看我的数据。

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

谢谢

5 个答案:

答案 0 :(得分:1)

如果您的网站位于端口string firstName; string lastName; 上并且您的服务器位于端口3002上,那么您必须指定整个服务器的位置

3010

答案 1 :(得分:1)

在AngularJS代码中指定整个url,并在express后端使用CORS中间件。

https://github.com/expressjs/cors

答案 2 :(得分:1)

这是在同一台机器上本地执行前端(AngularJs)和后端开发的糟糕方法。尝试使前端存储库适合由BE服务器托管并以下列方式使用它:

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

使用以下行作为公共baseUrl

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

这样做,在提交对prod环境的更改时,您不需要更新。

 $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'));

在角度4+的更高版本中,我们有初始配置中的设置。

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

答案 3 :(得分:1)

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

XMLHttpRequest cannot load .....

解决方案是更改API端点,将Access-Control-Allow-Origin标头设置为通配符*,或者设置使用JavaScript代码的页面的域。

For More Details on 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.

答案 4 :(得分:0)

你不能只写/ api / books。您需要指定在localhost上运行的API的端口号。 在你的情况下localhost:3010 / api / books

相关问题