'Why doesn't this simple API call to ASP.net work within ReactJS?
UsersController.cs
namespace testlol
{
[ApiController]
public class UsersController : ControllerBase
{
private readonly ILogger<UsersController> _logger;
static readonly Models.IUserRepository repository = new Models.UserRepository();
public UsersController(ILogger<UsersController> logger)
{
_logger = logger; //what is this ?
}
[HttpGet]
[Route("api/users")]
public IEnumerable<Models.UserModel> GetAllUsers()
{
return repository.GetAll();
}
[HttpPost]
[Route("api/user")]
[Consumes("application/json")]
public Models.UserModel PostUser(Models.UserModel item)
{
return repository.Add(item);
}
}
}
Where I then use the service in react: userService.js
export async function getAllUsers() {
const response = await fetch('/api/users');
return await response.json();
}
Then, I try to call it in a component:
import { getAllUsers } from "../services/userService.js"
...
useEffect(() => {
const getUserList = () => {
console.log("Getting user list ..");
getAllUsers()
.then(userList => {
console.log("User list: ")
console.log(userList)
setUsers(userList)
});
}
getUserList()
}, [])
This always yields the error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I'm not sure how the program isn't working. I saw that it could be a blank string, but I'm also currently storing some hardcoded values in another file:
public UserRepository()
{
Add(new UserModel { email = "[email protected]", password ="password" });
Add(new UserModel { email = "[email protected]", password ="admin" });
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
