CORS ASP.NET Core Web API missing “Access-Control-Allow-Origin” header when I’m trying to get data into my frontend (React + Vite) from backend API. In my backend, I get all responses 200.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json.Serialization;
namespace Bakis
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowOrigin", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
services.AddControllersWithViews().AddNewtonsoftJson(builder => builder.SerializerSettings.ReferenceLoopHandling
= Newtonsoft.Json.ReferenceLoopHandling.Ignore).AddNewtonsoftJson(builder => builder.SerializerSettings.ContractResolver = new DefaultContractResolver());
// Other service configurations
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
// Allow CORS
app.UseCors("AllowOrigin");
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}
import { useEffect, useState } from "react"
import { Ticket } from "../types/ticket"
import config from "../types/config";
const TicketList = () => {
const [tickets, setTickets] = useState<Ticket[]>([]);
useEffect(() => {
fetchTickets();
}, []); // Fetch tickets on component mount
const fetchTickets = async () => {
try {
const rsp = await fetch(`${config.baseApiUrl}/tickets`, {mode: 'cors'});
const ticketsData = await rsp.json();
setTickets(ticketsData);
} catch (error) {
console.error("Error fetching tickets:", error);
}
};
return (
<div>
<div className="row mb-7">
<h5 className="themeFontColor text-center">
All tickets
</h5>
</div>
<table className="table table-striped">
<thead>
<tr>
<th>Name</th>
{/* <th>Description</th> */}
{/* <th>Category</th> */}
</tr>
</thead>
<tbody>
{tickets.map((t) => (
<tr key={t.ticketId}>
<td>{t.TicketName}</td>
{/* <td>{t.Description}</td> */}
{/* <td>{t.TicketCategory}</td> */}
</tr>
))}
</tbody>
</table>
</div>
);
}
export default TicketList;
enter image description here
Cross-Origin Request Blocked: Same-Origin privacy policy prohibits reading the remote resource from https://localhost:4000/api/tickets (cause: Access-Control-Allow-Origin header missing from CORS request). Status code: 200.
Tried reordering UseCors
, chatgpt, reading other stackowerflow posts
Thuthutka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.