2

Here is the deal: I have a RESTapi on ASP.NET Core Web Api Server. When i'm trying to get data in Postman, there I do a http post request to controller like this http://localhost:5000/api/account/login with data(username, password) after that simply getting http get request and get data from sql server. I Understand that back-end server is all right. But I also have front-end side on Angular 2. I created a login component where input the info (i.e. username and password) on login page. So when I input info, angular take this, send me StatusCode 200 and navigate me to next page where I'm trying to do http get request to main data in the database through RESTapi. So when angular navigated me to the page with Main Data, it just throws 2 errors:
1)GET http://localhost:5000/Account/Login?ReturnUrl=%2Fapi%2Fwork 404 (Not Found)
2)Unexpected end of JSON input
Though in the Postman I'm simply getting Main Data after post request.
Here's piece of code from data.service.ts where all post and get method located:

getWorks(): Observable<IWork[]>{
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get(this._baseUrl + 'work')
            .map((result: Response) => {
                return result.json(); })
        .catch(this.handleError);
    }   



login(user : User) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.post(this._baseUrl + 'account/login', JSON.stringify(user), { headers: headers })
            .map((result: Response) => {
                return result.json();
            }).catch(this.handleError);
    }

Function when user's authorizing in login.component.ts

login() : void {
        let _authenticationResult: OperationResult = new OperationResult(true, '');
        this.dataService.login(this._user).subscribe((result: any) => {
            _authenticationResult.succeeded = result.succeeded;
            _authenticationResult.message = result.message;

            if(_authenticationResult.succeeded) {

                this.notificationService.printSuccessMessage('Welcome ' + this._user.username + '!');
                localStorage.setItem('user', JSON.stringify(this._user));
                this.router.navigate(['/list']);
                return result.status = "200"; 
            } else {
                this.notificationService.printErrorMessage(_authenticationResult.message);
            }
        }),
        error => console.error('Error: ' + error);
    }

And getting Main Data file list-work.component.ts

getData() {
        this.dataService.getWorks().subscribe(result => {
            this.works = result;
            this.subscribeToData();
        }, error => { 
            this.notificationService.printErrorMessage('Authentication reqired');
            this.utilityService.navigateToSignIn();
            console.error('Error: '+ error); });
    }

If it'll helpful here's piece of code from WebApi(.net core) where i retrieve data, but i think deal is not here, cause it's all working on Postman

[Authorize(Policy = "AdminOnly")]
    public async Task<IActionResult> Get()
    {
        if (await _authorizationService.AuthorizeAsync(User, "AdminOnly"))
        {
            IEnumerable<Work> _works = _workRepository
            .AllIncluding(c => c.Creator, t => t.Type, time => time.Time, s => s.Stage)
            .OrderBy(x => x.Id)
            .ToList();
            IEnumerable<WorkViewModel> _workVM = Mapper.Map<IEnumerable<Work>, IEnumerable<WorkViewModel>>(_works);

            return new OkObjectResult(_workVM);
        }
        else
        {
            StatusCodeResult _codeResult = new StatusCodeResult(401);
            return new ObjectResult(_codeResult);
        }
    }

Appriciate any help. Thanks!
Update 1(thanks for NotBad4U):

export class MyBaseRequestsOptions extends BaseRequestOptions { 
  headers: Headers = new Headers({ 'X-Requested-With': 'XMLHttpRequest' }); 
  withCredentials: any = true; 
}
export class DataService extends MyBaseRequestsOptions{
login(user : any) {
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');

        return this.http.post(this._baseUrl + 'account/login', JSON.parse(JSON.stringify(user)), { headers: headers })
            .map((result: Response) => {
                return result.json();
            }).catch(this.handleError);
    }
getWorks(): Observable<IWork[]>{
        let headers = new Headers();
        headers.append('Content-Type', 'application/json');
        return this.http.get(this._baseUrl + 'work' ,{ headers: headers })
            .map((result: Response) => {
                return console.log(result);
                 })
        .catch(this.handleError);
    }
8
  • Well the error is 404, which means the url is not found. You need to check the correct url :) Commented May 4, 2017 at 14:53
  • @AJT_82 It appears, when user is not authorized. Forgot to mention about that :) Commented May 4, 2017 at 14:55
  • Can you put a console log in the call .map((result: Response) => { return result.json(); }). I think you get an empty Response and the nexpected end of JSON input is raise by the result.json() call. Commented May 4, 2017 at 15:21
  • @NotBad4U Yes, you were right, it seem like its gone, after some modification, including your advice, thanks man, but the main goal is not reached..( 2 days im trying to authenticate, it seems like Angular doesnt remember my post request and ingoring like i didnt do that post request and just throws me an 404 status(unauthorized in my case) Commented May 5, 2017 at 11:25
  • @Muro Are you using cookies for register the authentification ? Commented May 5, 2017 at 12:43

1 Answer 1

2

I think your cookie is never stored and it's why you get a 404 (401 in your case). It's because for cross domain requests (CORS), you need to set the withCredentials of XHR to true to make the browser add cookies in your requests.

So in your app.module you have to set:

import {CookieService} from "./shared/cookie.service";

export class MyBaseRequestsOptions extends BaseRequestOptions {
    headers: Headers =  new Headers({
      'X-Requested-With': 'XMLHttpRequest'
    });
    withCredentials: boolean = true;
}

@NgModule({
  declarations: [
    AppComponent,
    ....
  ],
  imports: [
    ....
  ],
  providers: [
    CookieService,
    {
      provide: RequestOptions,
      useClass: MyBaseRequestsOptions
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
Sign up to request clarification or add additional context in comments.

2 Comments

Yeeeeeeeeeeeeeeeaaaaahhhh, just about 3 days I was setting up the issue! Thank you very much! I'm glad to met your answer! Thank you bro! I'm sure if you sometime will have some issue you'll find a man who'll help you to solve that :)
Finally we did it :) I'm happy to hear that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.