CORS跨域问题解决


.NET

var builder = WebApplication.CreateBuilder(args);

// 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();
//添加跨域策略1
builder.Services.AddCors(opts => {
    opts.AddPolicy("Cros", opt => opt.AllowAnyOrigin()
                                    .AllowAnyHeader()
                                    .WithExposedHeaders("X-Pagination"));
});
var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();
//使用跨域策略2
app.UseCors("Cros");

app.Run();

VUE前端(代理)

找到vue.config.js

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  transpileDependencies: true,
//代理
  devServer:{
    proxy:{
      '/api':{
          target:'http://localhost:5041/api',
          //允许跨域
          changeOrigin:true,
          ws:true,
          pathRewrite:{
            '^/api':""
          } 
      }
    }
  }
})

需要重启程序!

import axios from "axios";
import {ref} from "vue";

const json=ref("/json");
const http=ref("/api"); 
export const getImage=()=>{
    return axios.get(http.value+"/Image/GetImage");
}