事情是这样的:我在 ASP.NET Core Web Api 服务器 上有一个 RESTapi。当我尝试在 Postman 中获取数据时,我会像这样 http://localhost:5000/api/account/login
向 Controller 发出 http post 请求数据(用户名,密码)之后只需获取http get请求并从sql服务器获取数据。我知道后端服务器没问题。
但我在 Angular 2 上也有前端。我创建了一个登录组件,在登录页面上输入信息(即用户名和密码)。因此,当我输入信息时,Angular 会接受此信息,向我发送 StatusCode 200 并将我导航到下一页,在该页面中我尝试通过 RESTapi 对数据库中的主要数据执行 http get 请求。
因此,当 Angular 将我导航到包含主数据的页面时,它只会抛出 2 个错误:
1)GET http://localhost:5000/Account/Login?ReturnUrl=%2Fapi%2Fwork 404(未找到)
2)JSON 输入意外结束
虽然在 postman 中我只是在发布请求后获取主要数据。
以下是 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 core) 的一段代码,我在其中检索数据,但我认为交易不在这里,因为它都在 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);
}
最佳答案
我认为您的 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 { }
关于angular - JSON 输入意外结束 Angular 2(4) http get 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43786215/