'Getting a CORS error when trying to communicate between vuejs frontend and .NET 6 backend locally
I am trying to make a project where I have to communicate between front and back end. For the last two days I have been trying to fix this CORS error. While googling it seems everybody accepts the same kind of solution, but none of these solutions seem to work in my case. The error I am getting is:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:5003/Test/GetRandomlyMultipliedNumber?number=2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.
The request is working with Postman, which shows that the request url is working as intended. I have already tried to add a proxyserver for the vue frontend:
module.exports = {
configureWebpack: {
devServer: {
headers: { 'Access-Control-Allow-Origin': '*' }
}
}
}
In the backend i have tried making a policy:
using CrashService.Services.Interfaces;
using CrashService.Services.Implementations;
var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "MyPolicy",
policy =>
{
policy.WithOrigins("*");
});
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ICrashService, CrashServices>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors();
app.UseAuthorization();
app.MapControllers();
app.Run();
And adding CORS to the controller (found on official documentation: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api):
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
Current controller:
using Microsoft.AspNetCore.Mvc;
using CrashService.Services.Interfaces;
namespace PokerService.Controllers
{
[ApiController]
[Route("[controller]")]
public class TestController : ControllerBase
{
private readonly ICrashService _crashService;
public TestController(ICrashService crashService)
{
_crashService = crashService;
}
[HttpGet("GetRandomlyMultipliedNumber")]
public double GetRandomlyMultipliedNumber(double number)
{
try
{
return _crashService.GetMultipliedNumber(number);
} catch (Exception ex)
{
Console.WriteLine(ex.Message);
return 0;
}
}
}
}
Request in the frontend:
import axios from 'axios';
const baseUrl = 'http://localhost:5003/Test/GetRandomlyMultipliedNumber?number=2';
export async function getNumber() {
try {
let response;
response = await axios.get(baseUrl);
return response.data;
} catch {
console.log("error");
}
}
I have also tried manually adding the headers to the axios request.
I really do not know how to fix this anymore, so any help is welcome :^).
Solution 1:[1]
Thanks to MindSwipe for the actual answer!
For people with the same error this is what the final program.cs looked like:
using CrashService.Services.Interfaces;
using CrashService.Services.Implementations;
var builder = WebApplication.CreateBuilder(args);
var MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "MyPolicy",
policy =>
{
policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
});
});
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSingleton<ICrashService, CrashServices>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("MyPolicy");
app.UseAuthorization();
app.MapControllers();
app.Run();
Please mind that this solution is not really safe, as you allowing any header, method and origin.
A safer way is to actually add the correct origin:
builder.Services.AddCors(options =>
{
options.AddPolicy(name: "MyPolicy",
policy =>
{
policy.AllowAnyHeader().AllowAnyMethod();
policy.WithOrigins("http://localhost:8080");
});
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Jesse Oosterwijk |
