I'm trying to implement a system using React.js and ASP.NET Core 6.0 and wanna display the user detail of the session on front end. I use Axios to connect the front end to my back end and get an Axios Network Error.
localhost/:1 Access to XMLHttpRequest at 'https://localhost:****/api/home' from origin 'https://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have tried to use full url (https://localhost:3000/) and there is still an error. How can I fix this error?
Thanks!
HomeController.cs
using Microsoft.AspNetCore.Mvc;
namespace test.API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class HomeController : Controller
{
public class UserDetail
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
[HttpGet]
public ActionResult login()
{
UserDetail user = new UserDetail();
user.Name = User.Identity.Name;
return Ok(user);
}
}
}
App.js
import React, { Component } from 'react';
import './App.css';
import axios from 'axios';
class App extends Component {
constructor(props) {
super(props);
this.state = {
user: []
};
}
async componentDidMount() {
axios.get("https://localhost:****/api/home").then(response => {
console.log(response.data);
this.setState({
user: response.data.user,
});
}).catch((err) => {
console.log(err)
});
}
render() {
return (
<div className="row">
<div key={this.state.user.name}></div>
</div>
);
}
}
export default App;