平常开发中的几个经常使用跨域处理方式

设置express代理请求

在基于 vue-cli的项目中,在开发环境配置(config/dev.env.js)中设置代理,可以将全部 /apidomain开头的请求都经过 npm run dev启动的 express服务器重定向到目标接口
官方文档: https://vuejs-templates.githu...
proxyTable: {
      '/apidomain':{
        target:'http://localhost:prot',//或ip或域名。
        changeOrigin:true,
        pathRewrite: {
          '^/apidomain': ''
        }
      }
    },

若要经过IP在局域网访问h5,启动开发服务器的时候添加host参数便可
即package.json的dev命令配置以下
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js --host 0.0.0.0",html

关闭chrome安全策略实现跨域

windows中新建一个bat文件粘贴下面的命令便可以此模式打开
更多可参考: https://www.cnblogs.com/zhong...
cd "C:\Program Files (x86)\Google\Chrome\Application" 
chrome.exe --disable-web-security --user-data-dir=c:/CorsUserData

asp.net core 服务端的CORS跨域设置

官方文档: https://docs.microsoft.com/zh...
必读文章: 跨域资源共享 CORS 详解-阮一峰
在实际设置中,由于在h5端添加header参数产生了 预检(OPTIONS)请求,看了上述文章后将通用参数修改到了query参数中

1. 添加cors服务

public void ConfigureServices(IServiceCollection services)
{
    //若只有部分接口则定义一个或多个命名的 CORS 策略,并在运行时按名称而后选择的策略,经过特性标记去设置跨域 详情见文档
    services.AddCors();
}

2. 启用中间件

//读取配置文件中设置的容许跨域的域名 CorsOrigins为一个数组  设置["*"]则会容许全部
var origins = Configuration.GetSection("CorsOrigins").GetChildren().Select(s => s.Value).ToArray();
app.UseCors(e =>
{
    e.WithOrigins(origins).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
});
//Startup文件中Configuration对象的获取
public IConfiguration Configuration { get; }
public Startup()
{
    var builder = new ConfigurationBuilder()//...AddJsonFile($"appsettings.json");
    Configuration = builder.Build();
}

JSONP

JSONP只支持GET请求,CORS支持全部类型的HTTP请求。JSONP的优点在于支持老式浏览器,以及能够向不支持CORS的网站请求数据。
必读文章: 跨域资源共享 CORS 详解-阮一峰
相关文章
相关标签/搜索