I'm new to web programing and am trying to fetch user data from a .NET Core API using JavaScript but I have been getting a CORS Missing Allow Origin error. I'm aware that this is probably a common and easy issue to resolve but I haven't been able to figure out how to do so. And as mentioned in similar questions I also tried it with the " withCredentials: true" configs for the fetch.
I don't even know at this point whether the issue is server or client side. Could anyone point me in the right direction?
JavaScipt
function ApiController({id}){
const [user, setUser] = useState({});
useEffect(() => {
axios
.get('https://localhost:7278/User/' + id, {
headers: {
"Access-Control-Allow-Origin": "*",
'Content-Type': 'application/json'
}
})
.then(res => {
console.log(res);
})
.catch( err => {
console.log(err);
})
}, [id]);
UserController.cs
//------------------------------------------------------------------------------
/// <summary>The user controller.</summary>
[Route("[controller]")]
[ApiController]
public class UserController : ControllerBase {
/*
...
*/
[HttpGet("{userId}")]
public async Task<UserDto> GetUser(Guid userId) {
return await _userService.GetUser(userId);
}
Startup.cs
/*
...
*/
services.AddCors(options => {
options.AddDefaultPolicy(builder => {
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
/*
...
*/
app.UseCors(builder =>
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyHeader()
);
