我正在使用 asp.net 中的 API,并尝试从 JavaScript 文件中获取它,但我认为我的 URL 有问题。这是我的控制器和我想要达到的方法:
[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);
}
}
这是我的js文件中的fetch函数:
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');
}
});
“my-local-host”与我在这里写的不同。
您应该将js函数中的方法:'POST'更改为方法:'GET'