Home > Back-end >  Unable to communicate to .Net API from Angular project
Unable to communicate to .Net API from Angular project

Time:12-29

I am trying to create a login page using .Net Core Web API and Angular. On button click, the login method should be called and the API call should be done, but there is some kind of error. Here is the code for the 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);
}

This is working fine. I have checked in swagger.

Now the angular part.

The login service code:

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':'*' })})

          
      }

Here is the .ts file code:

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');
        }

      })

  }

When I try to login it gives me this error:

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"
    }
}

I cannot understand what's going on.

CodePudding user response:

Your API is returning a string value. However by default angular httpClient responseType is JSON. Hence when it tries to parse the string into JSON object it fails to do that and throws the exception.

While making the Http call you can tell that API response will be in text format instead of JSON like below:-

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

It should work then after,

  • Related