I'm trying to connect to the api with axios, but it gives 400 error. how do i solve it?
Api
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private readonly JwtDbContext context;
private readonly IConfiguration configuration;
public UserController(JwtDbContext context, IConfiguration configuration)
{
this.context = context;
this.configuration = configuration;
}
[HttpPost("[action]")]
public async Task<ActionResult<Token>> Login([FromForm] UserLogin userLogin)
{
User user = await context.Users.Include(u => u.UserRoles).ThenInclude(ur => ur.Role).FirstOrDefaultAsync(x=>x.Email == userLogin.Email && x.Password == userLogin.Password);
if(user != null)
{
TokenHandler tokenHandler = new TokenHandler(configuration);
Token token = tokenHandler.CreateAccessToken(user);
user.RefreshToken = token.RefreshToken;
user.RefrestTokenEndDate = token.Expiration.AddMinutes(3);
await context.SaveChangesAsync();
return Ok(token);
}
return null;
}
}
React
var config = {
method: 'post',
url: 'https://localhost:7024/api/User/Login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
userLogin : JSON.stringify({
'Email': document.getElementById('userName').value,
'Password': document.getElementById('password').value
})
};
Axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
I got this code from postman. postman request is going. but react is not going. Thanks in advance. ................................
CodePudding user response:
You need to set headers and body like this:
var config = {
method: "POST",
url: 'https://localhost:7024/api/User/Login',
headers: { 'Content-Type': 'multipart/form-data' },
body: {
'Email': document.getElementById('userName').value,
'Password': document.getElementById('password').value
}
}).then(response => response.json())
.then(data => console.log(data));
}
CodePudding user response:
It gives you 400 because you are sending data in invalid shape. When using [FromForm]
attribute on your controller method it means that method is expecting serialized form data as input (eg: Email=Mickey&Password=Mouse
) - when you are specifying 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' from the client(as you did).
JSON.stringify will give you just stringified javascript object, which is obviously not the same as serialized form string. You either create this serialized string manually or use something like const serialized = new URLSearchParams(new FormData(formElement)).toString()
, if you have form element on UI when submitting request. In your case it would be the simplest way to do something like this:
body: new URLSearchParams({
'Email': document.getElementById('userName').value,
'Password': document.getElementById('password').value
})
Also I noticed you put userLogin
key in axios config, which is unknown config parameter to axios, you should use body
- body: serializedString
.
All this can also be done with 'Content-Type': 'multipart/form-data'
which will allow you to send only key-value pairs in body - as previous comment suggested to you. It is up to you, both of these content types are supported by [FromForm]
attribute.