尝试在本地 vuejs 前端和 .NET 6 后端之间进行通信时出现 CORS 错误

Getting a CORS error when trying to communicate between vuejs frontend and .NET 6 backend locally

我正在尝试制作一个必须在前端和后端之间进行通信的项目。在过去的两天里,我一直在尝试修复这个 CORS 错误。谷歌搜索似乎每个人都接受相同类型的解决方案,但这些解决方案中的 none 似乎适用于我的情况。我得到的错误是:

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.

请求正在使用 Postman,这表明请求 url 正在按预期工作。我已经尝试为 vue 前端添加一个代理服务器:

module.exports = {
    configureWebpack: {
      devServer: {
        headers: { 'Access-Control-Allow-Origin': '*' }
      }
    }
  }

在后端我尝试制定一个策略:

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();

并将 CORS 添加到控制器(在官方文档中找到: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: "*")]

当前控制器:

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;
            }
        }

    }
}

前端请求:

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");
    }
}

我也尝试手动将 headers 添加到 axios 请求中。

我真的不知道如何解决这个问题,所以欢迎任何帮助:^)。

感谢 MindSwipe 的实际回答!

对于有同样错误的人,这是最终 program.cs 的样子:

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();

请注意,此解决方案并不真正安全,因为您允许任何 header、方法和来源。

更安全的方法是实际添加正确的来源:

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: "MyPolicy",
        policy =>
        {
            policy.AllowAnyHeader().AllowAnyMethod();
            policy.WithOrigins("http://localhost:8080");
        });
});