我正在创建一个有角度的应用程序,并且即使登录正确也想对某人进行身份验证时出现错误。
HttpErrorResponse {标头:HttpHeaders,状态:200,statusText: “确定”,网址:“ http://localhost:50518/api/Employee”,确定:错误,...}错误: 错误:语法错误:JSON中位于位置0的意外令牌s XMLHttpRequest.onLoad上的JSON.parse() (http://localhost:4200/vendor.js:7076:51)在 ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2743:31)在Object.onInvokeTask (http://localhost:4200/vendor.js:34894:33)在 ZoneDelegate.push ../ node_modules / zone.js / dist / zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2742:36)在 Zone.push ../ node_modules / zone.js / dist / zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2510:47)在 ZoneTask.push ../ node_modules / zone.js / dist / zone.js.ZoneTask.invokeTask [in invokeTask的[as invoke](http://localhost:4200/polyfills.js:2818:34) (http://localhost:4200/polyfills.js:3862:14)在 XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:3888:17)个文本: “测试一下” proto :对象标头:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ}消息:“解析期间的Http失败 for http://localhost:50518/api/Employee“名称:” HttpErrorResponse“好的: 错误状态:200 statusText:“确定”网址: “ http://localhost:50518/api/Employee” proto :HttpResponseBase
我的身份验证服务:
export class AuthenticationService {
header = new HttpHeaders({
"content-type" : "application/JSON"
})
constructor(
private http: HttpClient,
private config : ApiConfigService,
private router : Router) { }
login(username: string, password: string): Observable<HttpResponse<Authentication>>{
return this.http.post<Authentication>(`http://localhost:50518/api/Employee`, {
username: username,
password: password
}, {
headers : this.header,
observe : "body",
responseType : "text"
});
}
}
我不明白为什么会出现此错误,我认为它不是来自我的.Net Core API。
更新问题来自我的.Net Core API,我做了:return Ok()
,但是当我切换为return Json()
时,它可以工作。
答案 0 :(得分:0)
请检查您是否将正确的内容类型标头作为application / JSON传递。
答案 1 :(得分:0)
您返回的响应是有效的json吗?您可以发布从API获得的信息吗?看起来它正在尝试解析JSON,但是正在获取其他内容,也许是字符串?如果是这种情况,则需要为HTTP服务指定responseType。如果是字符串,则需要指定您要返回的“文本”。
这是您应该使用的Angulars HTTP服务的重载方法:(假设您要返回一个字符串):
/**
* Construct a POST request which interprets the body as text and returns it.
*
* @return an `Observable` of the body as a `string`.
*/
post(url: string, body: any | null, options: {
headers?: HttpHeaders | {
[header: string]: string | string[];
};
observe?: 'body';
params?: HttpParams | {
[param: string]: string | string[];
};
reportProgress?: boolean;
responseType: 'text';
withCredentials?: boolean;
}): Observable<string>;
您发布的内容应如下所示:
login(username: string, password: string): Observable<any>{
return this.http.post<any>(`http://localhost:50518/api/Employee`, {
username: username,
password: password
}, {
headers : this.header,
observe : "body",
responseType : "text"
});
}
据我了解,这里有2个问题:第一个是您的客户代码需要JSON,因为您在post调用中使用了通用参数,但是从API返回了字符串。如果您选择从API返回字符串,则需要从http.post
中删除通用参数然后在您的API代码中,返回Ok(“在这里输入您的字符串”)