item | version |
---|---|
tauri | 2.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.
首先你需要了解幾個概念:
什麼是 CORS
什麼是 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
什麼是簡單請求,爲什麼簡單請求不會觸發CORS檢查?
https://developer.mozilla.org/zh-CN/docs/Web/HTTP/CORS#%E7%AE%80%E5%8D%95%E8%AF%B7%E6%B1%82
爲什麼你在請求頭中設置
Access-Control-Allow-Origin: *
無效? Access-Control-Allow-Origin 是一個響應頭,在服務端設置。
如何在 Tauri 中解決這個問題
你可以在 js 中調用 rust 發送請求。但是我推薦你用官方的方案 @tauri-apps/plugin-http
:
安裝依賴
1pnpm add @tauri-apps/plugin-http
並在 src-tauri 工程的 Cargo.toml 中加入 tauri-plugin-http.
1[dependencies] 2tauri-plugin-http = "2.0.0-rc"
在 capabilities\default.json 中開啓相應的權限
1"permissions": [ 2 "http:allow-fetch", 3 "http:default", 4 { 5 "identifier": "http:default", 6 "allow": [{ "url": "https://**" }] 7 }
在 lib.rs 中註冊該插件
1 tauri::Builder::default() 2 .setup(|app| { 3 ... // 省略 4 }) 5 .plugin(tauri_plugin_shell::init()) // 其它插件 6 .plugin(tauri_plugin_http::init()) // 本插件
在前端調用(以 typescript 爲例)
1import {fetch} from "@tauri-apps/plugin-http"; 2/// fetch(...)