简体   繁体   中英

Angular 4 and ASP.Net MVC 5 : returns an Empty JSON in response

after merging angular app with asp.net MVC calling API from angular returns an empty JSON.

The angular and asp.net are in the same domain.

If I call the API With PostMan, I have a JSON with the result. but if I call it in the angular app my JSON result is empty.

Are there any tips for communicating angular app with asp.net MVC after merging and serving in the same domain?

Update 1:

The code that used to calling Webservice:

 getSheets(): Observable<Sheet[]> {
return this.http.get(this.config.apiUrl + '/api/SheetsRelationAPI', 
this.jwt())
  .map(this.extractData)
  .do(data => console.log('SheetsData:', data))  // debug
  .catch(this.handleError);
 }


/**
* Handle HTTP error
*/
 private handleError(error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
const errMsg = (error.message) ? error.message :
  error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
  }

// private helper methods

 private jwt() {
// create authorization header with jwt token
const currentUser = JSON.parse(atob(this.cookie.getCookie('currentUser')));
  if (currentUser && currentUser.access_token) {
  const headers = new Headers({ 'Authorization': 'Bearer ' + currentUser.access_token},
  );
  return new RequestOptions({ headers: headers });
  }
  }
   private extractData(res: Response) {
const body = res.json();
return body || [];
 }

Update 2:

I notice that my API if I called it from outside domain it respond 2 times:

inspecting network with google chrome inspect element:

the first response is "zone.js" initiator and the second response is an "other" initiator

If I call the API from inside of the Domain I just have a response from "zone.js" initiator and it returns an empty JSON.

Update 3

export class OtherComponent implements OnInit {
sheets: Sheet[] = [];
errorMessage: string;
constructor(private httpService: HttpService) {
    // this.sheets = this.ichartHttp.getSheets();
    // console.log(this.sheets);
}
getSheets() {
    this.httpService.getSheets()
        .subscribe(
        sheets => this.sheets = sheets,
        error => this.errorMessage = <any>error
        );
}

ngOnInit() {
    this.getSheets();
}
}

The Problem is with my Authentication methods, I use two types of authentication, MVC and WebAPI they conflict if I send a request to API under the same Domain.

So my Answer is: Your Angular Code looks good, take a look at your middleware project

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