item | version |
---|---|
tauri | 2.0.0-rc |
Prerequisites
When you use javascript at foo.com to access bar.com/api, you may encounter an error like the one below (but you are able to access it using 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.
First you need to understand a few concepts:
What is CORS
What are CORS preflighted requests and why using fetch etc. in js triggers CORS checking? And what is an OPTION request?
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests
What are simple requests and why will they not trigger preflighted requests?
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests
Why does setting
Access-Control-Allow-Origin: *
in your request header not work? Access-Control-Allow-Origin is a response header, not request header.
How to fix this in Tauri
You can call rust in js to send the request. But I recommend you to use the official solution @tauri-apps/plugin-http
:
Install dependencies
1pnpm add @tauri-apps/plugin-http
add tauri-plugin-http to Cargo.toml.
1[dependencies] 2tauri-plugin-http = "2.0.0-rc"
Enable the appropriate permissions in capabilities\default.json
1"permissions": [ 2 "http:allow-fetch", 3 "http:default", 4 { 5 "identifier": "http:default", 6 "allow": [{ "url": "https://**" }] 7 }
Register this plugin in lib.rs::run
1 tauri::Builder::default() 2 .setup(|app| { 3 ... // omit 4 }) 5 .plugin(tauri_plugin_shell::init()) // another plugin 6 .plugin(tauri_plugin_http::init()) // the plugin we need
Called it (in typescript, for example)
1import {fetch} from "@tauri-apps/plugin-http"; 2/// fetch(...)