Webview2 Tauri bypass CORS

Tauri bypass Cors
On this page

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):

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:

  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:

  1. Install dependencies

    1pnpm add @tauri-apps/plugin-http
    

    add tauri-plugin-http to Cargo.toml.

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

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

  2. 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  }
    
  3. 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
    

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

  4. Called it (in typescript, for example)

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