2017-05-04 76 views
2

這是處理:我有一個ASP.NET核心RESTapi Web Api服務器。當我試圖在Postman中獲取數據時,我在那裏用一個數據(用戶名,密碼)向控制器這樣的http://localhost:5000/api/account/login做了一個http post請求,然後簡單地獲取http請求並從sql server獲取數據。我明白後端服務器是好的。 但我也有前端方角2。我創建了一個登錄組件,在登錄頁面上輸入信息(即用戶名和密碼)。所以,當我輸入信息,角採取這一點,發送給我的StatusCode 200,並導航我到下一頁,我試圖通過RESTapi http請求數據庫中的主要數據。 所以角航行時,我與主要數據的頁面,它只是拋出2個錯誤:
1)GET http://localhost:5000/Account/Login?ReturnUrl=%2Fapi%2Fwork 404 (Not Found)
2)Unexpected end of JSON input
雖然在郵差我只是post請求後獲得主要數據。
下面是data.service.ts的一段代碼,所有POST和GET方法位於:
JSON輸入的意外結束Angular 2(4)http獲取請求

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); 
    } 

功能,當用戶在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); 
    } 

並獲得主數據文件列表授權-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); }); 
    } 

如果它會有所幫助這裏是從的WebAPI(.NET核心),其中i檢索數據的代碼,但我認爲這筆交易是不是在這裏,因爲這一切都在郵遞員上工作

[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任何幫助。謝謝!
更新1(感謝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); 
    } 
+0

嘛錯誤是404,這意味着未找到URL。你需要檢查正確的網址:) – Alex

+0

@ AJT_82看來,當用戶沒有被授權。忘了提及關於:) – Muro

+0

你可以把一個控制檯日誌在調用'.map((result:Response)=> {return result.json();})''。我認爲你會得到一個空的'Response','result.json()'調用會引發'JSON輸入的相關結束'。 – NotBad4U

回答

2

我想您的Cookie,但不會保存,它就是爲什麼你(在你的案件401)獲得404。這是因爲對於跨域請求(CORS),您需要將XHR的withCredentials設置爲true,以使瀏覽器在您的請求中添加Cookie。

因此,在您app.module你必須設置:

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 { } 
+1

Yeeeeeeeeeeeeeeeaaaaahhhh,大約3天我剛剛成立問題!非常感謝你!我很高興見到你的答案!謝啦兄弟!我敢肯定,如果你有時會有一些問題,你會發現一個人會幫助你解決這個問題:) – Muro

+0

最後我們做到了:)我很高興聽到這個消息。 – NotBad4U