Webview2 Tauri 繞過 CORS

Tauri bypass Cors
Webview2 Tauri 繞過 CORS
itemversion
tauri2.0.0-rc

前提

當你在 foo.com 使用 js 來訪問 bar.com/api 的時候,你可能會遇到下面這樣的錯誤(但你能夠使用 curl 訪問它):

1Access to fetch at 'bar.com/api' 
2from origin 'foo.com' has been blocked by CORS policy: 
3No 'Access-Control-Allow-Origin' header is present on the requested resource. 
4If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

首先你需要了解幾個概念:

  1. 什麼是 CORS

    https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS

  2. 什麼是 CORS 預檢請求,爲什麼在 js 中使用 fetch 等會會觸發CORS檢查?以及什麼是 OPTION 操作?

    https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS#%E9%A2%84%E6%A3%80%E8%AF%B7%E6%B1%82

  3. 什麼是簡單請求,爲什麼簡單請求不會觸發CORS檢查?

    https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS#%E7%AE%80%E5%8D%95%E8%AF%B7%E6%B1%82

  4. 爲什麼你在請求頭中設置 Access-Control-Allow-Origin: * 無效? Access-Control-Allow-Origin 是一個響應頭,在服務端設置。

    https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers

如何在 Tauri 中解決這個問題

你可以在 js 中調用 rust 發送請求。但是我推薦你用官方的方案 @tauri-apps/plugin-http

  1. 安裝依賴

    1pnpm add @tauri-apps/plugin-http
    

    並在 src-tauri 工程的 Cargo.toml 中加入 tauri-plugin-http.

    1[dependencies]
    2tauri-plugin-http = "2.0.0-rc"
    

    https://github.com/tauri-apps/tauri-plugin-http

  2. 在 capabilities\default.json 中開啓相應的權限

    1"permissions": [
    2  "http:allow-fetch",
    3  "http:default",
    4  {
    5    "identifier": "http:default",
    6    "allow": [{ "url": "https://**" }]
    7  }
    
  3. 在 lib.rs 中註冊該插件

    1    tauri::Builder::default()
    2        .setup(|app| {
    3           ... // 省略 
    4        })
    5        .plugin(tauri_plugin_shell::init()) // 其它插件
    6        .plugin(tauri_plugin_http::init())  // 本插件
    

    https://v2.tauri.app/plugin/http-client/

  4. 在前端調用(以 typescript 爲例)

    1import {fetch} from "@tauri-apps/plugin-http";
    2/// fetch(...)