【发布时间】:2021-12-27 12:48:53
【问题描述】:
我正在尝试使用 .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"
}
}
我不明白发生了什么。
【问题讨论】:
-
在您的 API 方法中,您返回的是字符串类型,而不是返回 json 对象或更改调用代码以接受字符串响应。
-
如何更改呼叫代码?你能帮忙吗?
-
尝试在你的客户端代码中添加这个 - http.get(url, {responseType: 'text'})
-
是的,现在工作!
-
我是否应该将此添加为答案,您是否会将其标记为已接受,以便对其他人也有用?