Unexpected token s in JSON at position 0 at JSON.parse

osyris 236 Reputation points
2021-12-01T19:18:07.867+00:00

Im trying to create a sign up system with Angular
but i get the error:
"Unexpected token s in JSON at position 0 at JSON.parse"
every single time

asp net core :

namespace RestaurantProject.Controllers  
{  
    [Route("api/[controller]")]  
    [ApiController]  
    public class AuthenticationController : ControllerBase  
    {  
        private readonly ApplicationDbContext _dbContext;  
        private readonly UserManager<ApplicationUser> _userManager;  
        private readonly RoleManager<ApplicationRole> _signInManager;  
  
        public AuthenticationController(ApplicationDbContext dbContext,  
            UserManager<ApplicationUser> userManager,  
           RoleManager<ApplicationRole> roleManager)  
        {  
            _dbContext = dbContext;  
            _userManager = userManager;  
            _signInManager = roleManager;  
        }  
  
        [HttpPost("Client-Register")]  
        public async Task<IActionResult> ClientReg(ClientRegDto dto)  
        {  
             
                var exist = await _dbContext.Users.FirstOrDefaultAsync(x => x.Email == dto.Email);  
  
                if (exist != null)  
                    return BadRequest("Email Taken");  
                 
  
                var user = new ApplicationUser  
                {  
                    Email = dto.Email,  
                    FirstName = dto.FirstName,  
                    LastName = dto.LastName  
                };  
            try  
            {  
                var result = await _userManager.CreateAsync(user, dto.PassWord);  
            }catch (Exception ex)  
            {  
                return BadRequest(ex.Message.ToString());  
            };  
  
  
            return Ok("succes");  
  
            
            
        }  
  
  
  
    }  
}  

angular service:

 SignUp(val: any){  
    return this.http.post("https://localhost:7010/api/Authentication/Client-Register", val, { observe: "response"});  
  }  

angular component

  Registrate(){  
    this.auth.SignUp(this.val).subscribe(  
      data => console.log(data),  
      error => {  
        console.log(error)  
        if(error.ok == false){  
         this.error = true;  
        }  
        this.status = error.error  
      },  
       
       );  
  }  

the error that i get:

154251-error.png

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,141 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,247 questions
0 comments No comments
{count} votes

Accepted answer
  1. osyris 236 Reputation points
    2021-12-01T23:52:07.143+00:00

    I already found it haha
    Looking at the asp net core 6 template

      var user = new ApplicationUser();
                user.UserName = dto.FirstName;
                user.EmailConfirmed = true;
    

    thats the solution

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. AgaveJoe 26,186 Reputation points
    2021-12-01T21:18:14.733+00:00

    According to the error the client expects a JSON string response but your design returns a string; return Ok("succes");.

    var result = JSON.parse("success");
    

    VM123:1 Uncaught SyntaxError: Unexpected token S in JSON at position 0
    at JSON.parse (<anonymous>)
    at <anonymous>:1:19

    I'm not an angular expert but it is odd to expect a JSON string and need to use JSON.parse(). I would return the content type application/json.

    0 comments No comments

  2. osyris 236 Reputation points
    2021-12-01T23:28:16.76+00:00

    Thanks for your response Joe,

    After doing some research on stackoverflow
    I found out that

    this:
    return this.http.post("url", val, { observe: "response"});
    needs to be this:
    return this.http.post("url",val, { responseType: 'text'})

    so if anybody comes up with that error in angular this would be helpfull to know.

    But I still have to problem wich is in asp net core now

    still using this code:

            [HttpPost("Client-Register")]
            public async Task<IActionResult> ClientReg(ClientRegDto dto)
            {
                    var exist = await _dbContext.Users.FirstOrDefaultAsync(x => x.Email == dto.Email);
                    if (exist != null)
                        return BadRequest("Email Taken");
                var user = new ApplicationUser();
                user.Email = dto.Email;
                user.FirstName = dto.FirstName;
                user.LastName = dto.LastName;
    
                try { await _userManager.CreateAsync(user, dto.PassWord);
                }catch (Exception ex)
                {BadRequest(ex);}
                return BadRequest("Failed to Registrer");
            }
    

    I have done debugging with breakpoints and the dto has value so the "var user" has value
    so i think this is were the problem lays:

    await _userManager.CreateAsync(user, dto.PassWord)
    

    in the microsoft sql server I checked all the collums on "Allow null" exect for the Id (Guid) offcourse
    the error in the console log using the code above:

    error: "Failed to Registrer"
    headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
    message: "Http failure response for https://localhost:7010/api/Authentication/Client-Register: 400 OK"
    name: "HttpErrorResponse"
    ok: false
    status: 400
    statusText: "OK"
    url: "https://localhost:7010/api/Authentication/Client-Register"
    

    there is not really that much information
    but it does hit the end of the code showing my own badrequest text "Failed to Registrer" wich is a good thing

    so am i not allowed to only signup with email, and 2 of my own collums ( firstname and Lastname) even though i set "Alllow null" in the database?
    or am i using the wrong options for creating a account maybe "_userManager.CreateAsync" no longer works in NET 6 ?

    Looking forward to a reply so I can continue with my work.
    Thanks,

    0 comments No comments