简体   繁体   中英

Angular using Http request doesn't work

I'm trying to populate data from my DB using Angular and some API services.

My code:

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

And my API GET() :

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

No data is showing. I'm pretty sure the errors is popping because the this.User.Identity.Name is passed wrongly, but I'm confused.

If I change the method from GetTripsByUsername to GetAllTrips , which select all the trips without filter, then the data is shown properly in the page.

The function it self works, if I use it via PostMan, it recognize my cookie and bringing me the correct trips(inside postMan) but on the page it doesn't work ..

It doesn't because your angular application is not authenticated and this.User.Identity.Name is null.
You need to send credential in your angular code like that:

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

But it depends on your authentication mecanism, This code will not work for Oauth or Basic authentication. If you use Oauth, you must send the Authorization header containing the authorization token.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM