I'm currently utilizing an API in my asp.net project and attempting to access it from my JavaScript file. However, I suspect there may be an issue with the URL I am using. Here is the controller and method I am trying to retrieve:
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
[HttpGet("get-user-by-id")]
public async Task<IActionResult> GetUser(string email, string
password)
{
var result = await _userService.GetUser(email, password);
if (result == null) return NotFound();
return Ok(result);
}
}
Below is the fetch function within my JavaScript file:
fetch('https://"mylocalhost"/api/User/get-user-by-id', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ email, password }),
})
.then(function (response) {
if (!response.ok) {
throw new Error('HTTP error! Status: ' + response.status);
}
return response.json();
})
.then(function (data) {
console.log('Login success:', data);
window.location.href = 'profile.html';
})
.catch(function (error) {
console.error('Login error:', error.message);
if (error.message.includes('401')) {
console.log('Incorrect username or password');
} else {
console.log('An error occurred during login');
}
});
Please note that "my-local-host" is different from what I have mentioned here.