[英]Angular 4 and ASP.Net MVC 5 : returns an Empty JSON in response
將angular app與asp.net MVC合並,從angular調用API后,返回空JSON。
angular和asp.net在同一個域中。
如果我使用PostMan調用API,則結果中將包含一個JSON。 但是如果我在angular應用程序中調用它,我的JSON結果為空。
在同一域中合並並提供服務后,是否有任何技巧可與asp.net MVC通信angular應用程序?
更新1:
用來調用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 || [];
}
更新2:
我注意到,如果我從外部域調用我的API,它會響應2次:
用google chrome檢查網絡檢查元素:
第一個響應是“ zone.js”啟動器,第二個響應是“其他”啟動器
如果我從域內部調用該API,則只會收到“ zone.js”啟動器的響應,並且它將返回一個空的JSON。
更新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();
}
}
問題出在我的身份驗證方法上,我使用兩種類型的身份驗證,即MVC和WebAPI,如果我向同一域下的API發送請求,它們會沖突。
所以我的答案是:您的Angular代碼看起來不錯,請看一下您的中間件項目
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.