这是交易:我在ASP.NET Core上有一个RESTapi Web Api服务器。当我试图在邮递员中获取数据时,我会向控制器发送一个http发布请求,如此http://localhost:5000/api/account/login
,其中包含数据(用户名,密码),之后只需获取http获取请求并从SQL Server获取数据。我明白后端服务器是可以的。
但我也有 Angular 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
虽然在邮递员中我只是在发布请求后获得主要数据
这是来自data.service.ts的一段代码,其中所有的post和get方法都位于:
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);
}
获取主数据文件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); });
}
如果它从WebApi(.net核心)获取有用的代码片段,我会检索数据,但我觉得交易不在这里,因为它全部在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);
}
}
提供任何帮助。谢谢!
更新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 :(得分:2)
我认为你的cookie永远不会被存储,这就是你获得404
(在你的情况下为401)的原因。这是因为对于跨域请求(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 { }