【问题标题】:Angular using Http request doesn't work使用 Http 请求的 Angular 不起作用
【发布时间】:2018-02-06 15:52:42
【问题描述】:

我正在尝试使用 Angular 和一些 API 服务从我的数据库中填充数据。

我的代码:

        $http.get("/api/trips")
            .then(function (response) {
                angular.copy(response.data, vm.trips);
            }, function (error) {
                vm.errorMessage = "Failed to load data: " + error
            });

还有我的 API GET()

        [HttpGet("")]
        public IActionResult Get()
        {
                var results = _repository.GetTripsByUsername(this.User.Identity.Name);
                return Ok(Mapper.Map<IEnumerable<TripViewModel>>(results));
         }

没有数据显示。我很确定错误正在弹出,因为 this.User.Identity.Name 传递错误,但我很困惑。

如果我将方法从 GetTripsByUsername 更改为 GetAllTrips ,即选择所有未过滤的行程,则数据将正确显示在页面中。

它自己工作的功能,如果我通过 PostMan 使用它,它会识别我的 cookie 并为我带来正确的旅行(在 postMan 内),但在页面上它不起作用..

【问题讨论】:

  • GetTripsByUsername 方法是否显示任何特定的错误消息?网络选项卡中返回的错误代码是什么?
  • 我在控制台上看不到任何错误,GetTripsByUsername 通过 Postman @AlexBeugnet 工作,我只需输入路径并返回正确的行程。
  • 不,我的意思是通过您的申请,而不是 Postman。你说I'm pretty sure the errors is popping...。我相信它来自您的角度应用程序,因此“加载数据失败:”中包含的错误消息是什么以及您的浏览器返回的错误代码?
  • 就是这样。它没有说“加载数据失败”,而且我找不到任何错误消息。如果我将路径更改为 tripss,那么它会这样做。这就是为什么我认为它“正常工作”,但 Identity.name 没有被识别或什么的。 @AlexBeugnet
  • 看看这个旧帖子:stackoverflow.com/questions/41337145/…我相信这就是你想要做的

标签: javascript angularjs asp.net-core


【解决方案1】:

这不是因为您的 Angular 应用程序未经过身份验证并且 this.User.Identity.Name 为空。
您需要像这样在 Angular 代码中发送凭据:

$http.get("/api/trips", { withCredentials: true })
            .then(function (response) {
                angular.copy(response.data, vm.trips);
            }, function (error) {
                vm.errorMessage = "Failed to load data: " + error
            });

但这取决于您的身份验证机制,此代码不适用于 Oauth 或 Basic 身份验证。如果您使用 Oauth,则必须发送包含授权令牌的 Authorization 标头。

【讨论】:

  • 我使用 cookie 身份验证,添加这个不起作用.. 仍然是同样的问题。不过听起来不错,那是我怀疑发送的身份有误。还有其他想法吗?
  • 找到一种使用 cookie 发布应用程序身份验证的方法
  • 不确定我是否理解你:S
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多