vue幾個常用跨域處理方式介紹,vue幾個跨域
設定express代理請求
在基於vue-cli的項目中,在開發環境配置(config/dev.env.js)中設定代理,能夠將所有/apidomain開頭的請求都通過npm run dev啟動的express伺服器重新導向到目標介面
官方文檔:https://vuejs-templates.github.io/webpack/proxy.html
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",
關閉chrome安全性原則實現跨域
windows中建立一個bat檔案粘貼下面的命令即可以此模式開啟
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-cn/aspnet/core/security/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的網站請求資料。