vue 使用axios请求,后台进行跨域处理
作者:秋名
撰写时间:2020 年 8 月 19 日
什么是跨域问题呢?
后台地址44310:https://localhost:44310/api/Products/Getproducts
前端地址8080:http://localhost:8080/#/
两者的端口不一致,浏览器就会实行保护,不允许跨域到别的网站去请求,为了允许别人过来访问我的数据,所以就产生了跨域
解决办法1:vue 使用axios请求和vue-cli这种脚手架工具实现跨越传输
解决办法2:使用CORS,服务器可以在显式允许某些跨域请求时拒绝其他跨域请求
public void ConfigureServices(IServiceCollection services)
{
var conSer=Configuration.GetSection("Constr");
SqlHelper.Constr = conSer.Value;
//Cors:跨域资源共享,允许服务器放宽同源策略。使用CORS,服务器可以在显式允许某些跨域请求时拒绝其他跨域请求。CORS是相比其他跨域技术(比如JSONP)更安全、更灵活
//AddPolicy 使用政策
//AllowAnyOrigin 允许任何来源
//AllowAnyHeader允许任何的Header头部标题 有关头部标题如果不设置就不会进行限制
//AllowAnyMethod允许跨域策略允许所有的方法:GET/POST/PUT/DELETE 等方法 如果进行限制需要 AllowAnyMethod("GET","POST") 这样来进行访问方法的限制
services.AddCors(o => o.AddPolicy("any", p => p.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod()));
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//使用跨域
app.UseCors();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
//Route:路由
//api/控制器/方法名
//api/Products/Getproducts
[EnableCors("any")]//调用跨越的政策
[Route("api/[controller]/[action]")]
[ApiController]
public class ProductsController : ControllerBase
{
public List<Products> Getproducts() {
List<Products> productList = Products.GetProductList();
return productList;
}
}