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(...)