vue幾個常用跨域處理方式介紹,vue幾個跨域

來源:互聯網
上載者:User

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的網站請求資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.