Currently I'm trying to separate the front-end (ClientApp client-side application) and the back-end (ASP .NET Core 3.1). I'm using the ASP .NET Core with React.js
project template in VS. What I want to achieve is: Two apart projects within a solution. The front-end and the back-end have different port number and it's possible to get data from database via controller in the back-end then a React component can receive data to render in browser.
Basically I followed the solution from this blog. But still got error. I'm using the following code in Account component to call the Index method in Accounts controller.
const response = await fetch(`${process.env.REACT_APP_API_URL}/Accounts`, { mode: 'no-cors' });
Here the AccountsController
[EnableCors("AllowOrigin")]
public class AccountsController : Controller
{
private readonly DEMOWTSSPortalContext _context;
public AccountsController(DEMOWTSSPortalContext context)
{
_context = context;
}
// GET: Accounts
public IEnumerable<Accounts> Index()
{
return _context.Accounts.ToList();
}
}
I also added the code to solve the CORS error.
In ConfigureServices
I added services.AddCors(allowsites => {allowsites.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
. And in Configure
I added app.UseCors(options => options.AllowAnyOrigin());
.
But When I starting the ClientApp
from npm and starting back-end from IIS in VS. The data is not shown. It says Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
Dose anyone have some idea how to fix it?