How to solve CORS error: No Access-Control-Allow-Origin header?
Fix CORS error on API side; Check origin, OPTIONS preflight, and cookied request settings with Express and ASP.NET Core examples.
in the browser consoleNo 'Access-Control-Allow-Origin' header is presentmessage indicates that JavaScript is not allowed to read the response from a different origin. This is why it is possible for the API to fail in the browser while running in Postman: Postman does not implement the browser's CORS checking.
The solution is to define the appropriate CORS policy on the API that produces the response or the proxy in front of it. Request sent by the clientAccess-Control-Allow-OriginAdding does not create this permission; This header must be included in the server response.
1. Determine the exact origin value
origin; It is a combination of protocol, host and port.http://localhost:5173, http://localhost:3000Andhttps://localhost:5173are different origin values. The URL path is not part of origin; to the permission list/dashboarddo not add.
Open the Network tab in developer tools. The actual URL of the failed request,Originits title and any previous work, if any.OPTIONSReview your request. The redirect may appear as a CORS error in the console when the 401, 404, or 500 response also does not carry a CORS header. First you need to understand the actual HTTP result.
2. Define controlled permission for Express
The example below isexpressAndcorsThe packages are for an installed CommonJS application. Write your interface address in production to the permission list; Add middleware before routes:
const express = require("express");
const cors = require("cors");
const app = express();
app.use(cors({
origin: ["http://localhost:5173", "https://app.example.com"],
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization"]
}));
app.use(express.json());
app.get("/api/health", (req, res) => res.json({ ok: true }));
app.listen(3000);
This middleware, used at the application level, also meets preflight requests. If another middleware is blocking the OPTIONS request before, correct the order. Do not add method or origin values to the list that your API does not need.
3. Use named policy for ASP.NET Core
In an ASP.NET Core application using minimal hosting, service registration and middleware are required together. AvailableProgram.csAdd it where appropriate to the flow:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services.AddCors(options =>
{
options.AddPolicy("Frontend", policy =>
policy.WithOrigins("http://localhost:5173", "https://app.example.com")
.WithMethods("GET", "POST", "PUT", "DELETE")
.WithHeaders("Content-Type", "Authorization"));
});
var app = builder.Build();
app.UseRouting();
app.UseCors("Frontend");
app.UseAuthorization();
app.MapControllers();
app.Run();
Maintain your own authentication configuration in the application that uses authentication. Deploy the CORS middleware after routing and before authorization. Do not add unnecessary slashes at the end of origin values.
4. Do not use wildcards for cookie requests
On the client for cross-origin fetch that sends session cookiecredentials: "include"must. Concrete origin and location that are also allowed on the serverAccess-Control-Allow-Credentials: truemust be found. Express examplecredentials: true, ASP.NET Core policyAllowCredentials()can be added.
Request with cookiesAccess-Control-Allow-Origin: *cannot be used. Additionally, the CORS settingSameSite, Secureor the browser does not override the third-party cookie policy. Fixing CORS does not mean that every cross-site session scenario will work automatically.
5. Verify Preflight response
Run the following request in terminal for the actual endpoint of your API. Instead of curl alias in Windows PowerShellcurl.exeuse:
curl -i -X OPTIONS https://api.example.com/api/items \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: content-type,authorization"
Allowed origin, method and headers must appear in the response. Then check the actual POST response as well. curl does not implement CORS; It just helps you review the titles. Final verification must be done in the browser.
If error persists, review proxy and actual response
With a proxy, if the application adds the same header twice, the browser may reject the response. If the OPTIONS request is redirected to the login page or a 403 is returned by the proxy, the API policy may not kick in at all. To allocate the cache according to origin in server responses that select dynamic originVary: OriginAlso check its behavior.
Short guide
Common mistake
mode: "no-cors"Trying to solve the problem using . This mode usually produces an opaque response that JavaScript cannot read; does not provide a readable JSON API response.