Webview2 Tauri bypass CORS

itemversion
tauri2.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):

Access to fetch at 'bar.com/api' 
from origin 'foo.com' has been blocked by CORS policy: 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
If 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:

  1. What is CORS https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
  2. 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
  3. What are simple requests and why will they not trigger preflighted requests? https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#simple_requests
  4. Why does setting Access-Control-Allow-Origin: * in your request header not work?
    Access-Control-Allow-Origin is a response header, not request header.

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

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

pnpm add @tauri-apps/plugin-httppnpm add @tauri-apps/plugin-httppnpm add @tauri-apps/plugin-httppnpm add @tauri-apps/plugin-http
[dependencies]

tauri-plugin-http = "2.0.0-rc"

    Enable the appropriate permissions in capabilities\default.json

     "permissions": [
     "http:allow-fetch",
     "http:default",
     {
     "identifier": "http:default",
     "allow": [{ "url": "https://**" }]
     }

    Register this plugin in lib.rs::run

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

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

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

    Leave a Comment