http error 400 is reported using fetch when posting data and getting back validation message in vuejs and .net6

Viewed 31

Vuejs 3.2.32 front end and .net 6 server

I am a beginner front end with vuejs / js/ts

I have a register model with 'required' set and a register form and I am using fetch to post data. I get back the expected validation message that a field is required if I have left it blank and i display that message to the user but chrome logs it as a 400 error even though its handled. Is this normal or have I missed something?

<script setup>
import { ref } from 'vue'

const user = {
    firstName: "",
    lastName: "",
    displayName: "",
    username: "",
    password: ""
}

const formErrors = ref(null);

const register = () => {
    fetch('https://localhost:7224/account/register', {
        method: 'POST',
        body: JSON.stringify({
            displayName: user.displayName,
            firstName: user.firstName,
            lastName: user.lastName,
            password: user.password,
            username: user.username
        }),
        headers: {
            'content-type':'application/json; charset=UTF-8',
        }
    })
    .then(async response => {
        const data = await response.json();
        if (!response.ok) {
            formErrors.value = data.errors;                
            const error = "error";
            return Promise.reject(error);
        }
    })
    .catch(error => {
        console.log("There was an error!", error);
    });
}

chrome dev tools with error

Model

public class RegisterForm
{
    [Required]
    [JsonPropertyName("displayName")]
    public string DisplayName { get; set; }

    [Required]
    [JsonPropertyName("firstName")]
    public string FirstName { get; set; }

    [Required]
    [JsonPropertyName("lastName")]
    public string LastName { get; set; }

    [Required]
    [JsonPropertyName("password")]
    public string Password { get; set; }

    [Required]
    [JsonPropertyName("username")]
    public string Username { get; set; }
}

Account controller

    [Authorize]
[EnableCors("VueCorsPolicy")]
[ApiController]
[Route("[controller]")]
public class AccountController : ControllerBase
{
    private IIdentityService _identityService;

    public AccountController(IIdentityService identityService)
    {
        _identityService = identityService;            
    }       

    [AllowAnonymous]
    [HttpPost("register")]
    public async Task<IActionResult> Register(RegisterForm registerForm)
    {
        var result = true; //await _identityService.Register(registerForm);
        if (result)
        {
            //send confirmation email
            return StatusCode(200, new { message = "Registration successful, confirm account by checking email" });
            //Ok(new { message = "Registration successful, confirm account by checking email" });
        }
        else
        {
            return StatusCode(500);
        }            
    }
}
0 Answers
Related