我正在嘗試使用 .net core web api 和 angular 創建登錄頁面。應呼叫按鈕單擊登錄方法并應完成 api 呼叫,但會產生某種錯誤。這是api的代碼->
[HttpGet]
[Route("LoginBankUser")]
public IActionResult LoginBankUser(string username, string password)
{
MongoClient mongoClient = new MongoClient(_configuration.GetConnectionString("con1"));
users = mongoClient.GetDatabase("bankstatement")
.GetCollection<UserLogin>("userlogin");
List<UserLogin> userList = users.Find(user => true).ToList();
foreach(var u in userList)
{
if(u.username.Equals(username) && u.password.Equals(password))
{
return Ok(u.username);
}
}
string resStr = "nota";
return Ok(resStr);
}
這作業正常。我已經檢查過招搖。
現在是角度部分。登錄服務代碼->
private loginUrl = 'https://localhost:44340/api/Login/';
loginMethod(username:string, password:string): any {
console.log(username)
console.log(password)
return this.http.get(this.loginUrl "LoginBankUser?username=" username
"&password=" password,
{ headers:new HttpHeaders({
'content-type': 'text/plain; charset=utf-8' ,
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Method':'*' })})
}
這是 .ts 檔案代碼->
login_method(username:string, password:string):void
{
this.obj.loginMethod(username, password).subscribe(data=>
{
console.log(data)
if(data.toString() != "nota"){
//save to local storage
localStorage.setItem('bankUserName', data.toString());
this.router.navigate(['/home']);
}
else{
alert('Invalid credentials');
}
})
}
當我嘗試登錄時,它給了我這個錯誤->
error: {error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse (<anonymous>) at XMLHtt…,
{
"headers": {
"normalizedNames": {},
"lazyUpdate": null
},
"status": 200,
"statusText": "OK",
"url": "https://localhost:44340/api/Login/LoginBankUser?username=admin&password=admin",
"ok": false,
"name": "HttpErrorResponse",
"message": "Http failure during parsing for https://localhost:44340/api/Login/LoginBankUser?username=admin&password=admin",
"error": {
"error": {},
"text": "nota"
}
}
我不明白這是怎么回事。有人幫忙請!
uj5u.com熱心網友回復:
您的 API 正在回傳一個字串值。但是默認情況下 angular httpClientresponseType 是JSON. 因此,當它嘗試決議stringintoJSON物件時,它無法決議并拋出例外。
在進行 Http 呼叫時,您可以看出 API 回應將采用以下text格式而不是JSON以下格式:-
http.get(url, {responseType: 'text'})
它應該作業然后之后,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/395819.html
