JSON输入的意外结束Angular 2(4)http获取请求
这是处理:我有一个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);
}
我想您的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 { }
嘛错误是404,这意味着未找到URL。你需要检查正确的网址:) – Alex
@ AJT_82看来,当用户没有被授权。忘了提及关于:) – Muro
你可以把一个控制台日志在调用'.map((result:Response)=> {return result.json();})''。我认为你会得到一个空的'Response','result.json()'调用会引发'JSON输入的相关结束'。 – NotBad4U