【问题标题】:Unable to communicate to .Net API from Angular project无法从 Angular 项目与 .Net API 通信
【发布时间】: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'})
  • 是的,现在工作!
  • 我是否应该将此添加为答案,您是否会将其标记为已接受,以便对其他人也有用?

标签: asp.net .net angular


【解决方案1】:

您的 API 正在返回一个字符串值。但是默认角度httpClient responseType 是JSON。因此,当它尝试将 string 解析为 JSON 对象时,它无法做到这一点并抛出异常。

在进行 Http 调用时,您可以知道 API 响应将采用 text 格式,而不是 JSON,如下所示:-

http.get(url, {responseType: 'text'})

它应该在之后工作,

【讨论】:

    猜你喜欢
    • 2022-12-01
    • 2022-08-19
    • 2020-09-29
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2011-03-15
    • 2019-01-24
    • 1970-01-01
    相关资源
    最近更新 更多