最近在写一个网站,例行跨域问题。如何解决呢?
Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
跨域问题是什么原因造成的?
跨域问题造成的原因是浏览器约定的同源策略。简单说就是同源策略是浏览器的行为,是为了保护本地数据不被JavaScript代码获取回来的数据污染。
后端解决办法:
Program.cs代码
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// 第一步声明一个变量
string CORS1 = "mycors";//名字可以随意取
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// 配置服务
builder.Services.AddCors(options =>
{
options.AddPolicy(CORS1,
builder => builder.AllowAnyOrigin()
.WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")
);
});
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors(CORS1); // 如果使用了Mvc,这句要放在app.useMvc()之前!!!
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
前端解决办法:
在vue.config.js中加入这个代码,配置一个代理
module.exports = defineConfig({
transpileDependencies: true,
lintOnSave: false,
devServer: {
proxy: {
'/api': {
target: 'https://localhost:7172/api', //后端接口地址
changeOrigin: true, //是否允许跨越
pathRewrite: {
'^/api': '' //路径重置,
}
}
},
},
})
在发送请求,创建请求实例的时候代码
const $http = axios.create({
baseURL: "/api",
timeout: 2000,
headers: {
"Content-Type": "application/json,charset=utf-8"
}
});