【发布时间】:2017-10-02 19:55:04
【问题描述】:
这是交易:我在 ASP.NET Core Web Api Server 上有一个 RESTapi。当我试图获取数据在 Postman 中时,我会向控制器发出一个 http post 请求,像 http://localhost:5000/api/account/login 这样带有数据(用户名,密码),然后简单地获取 http get 请求并从中获取数据sql服务器。我知道后端服务器没问题。
但我也有 Angular 2 的前端。我创建了一个登录组件,在登录页面上输入信息(即用户名和密码)。因此,当我输入信息时,角度取这个,向我发送 StatusCode 200 并导航到我试图通过 RESTapi 对数据库中的主要数据进行 http 获取请求的下一页。
因此,当 Angular 将我导航到包含主数据的页面时,它只会引发 2 个错误:
1)GET http://localhost:5000/Account/Login?ReturnUrl=%2Fapi%2Fwork 404 (Not Found)
2)Unexpected end of JSON input
虽然在 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);
}
【问题讨论】:
-
那么错误是404,这意味着找不到url。您需要检查正确的 url :)
-
@AJT_82 当用户未被授权时出现。忘记提了:)
-
你能在电话
.map((result: Response) => { return result.json(); })中放一个控制台日志吗?我认为你得到一个空的Response,nexpected end of JSON input被result.json()调用加注。 -
@NotBad4U 是的,你是对的,它似乎已经消失了,经过一些修改,包括你的建议,谢谢,但主要目标没有达到..(我试图验证 2 天,似乎 Angular 不记得我的发帖请求和 ingoring 就像我没有做那个发帖请求,只是给我一个 404 状态(在我的情况下未经授权)
-
@Muro 你在使用cookies来注册认证吗?
标签: angular typescript post asp.net-web-api get