Tauri app api request blocked by cors with api built with django restframework
Asked Answered
C

2

5

https://tauri.localhost' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

I have added https://tauri.localhost to my cors configuration in my api but it still throws the same error. CORS_ALLOWED_ORIGINS = [ "http://localhost:3001", "http://localhost:3003", "tauri://localhost", "https://tauri.localhost"," ]

Comprehensible answered 21/6, 2023 at 9:24 Comment(1)
The error message indicates that the client is including a header named access-control-allow-origin in the request, which doesn't make sense since that header is a response header.Sheugh
R
4

I hope you are using http client provided by Tauri itself. I've encountered the same problem when I tried to call APIs in my tauri app using axios/fetch then after some research I used the http module provided by tauri and everything worked fine.

Rafter answered 6/10, 2023 at 9:30 Comment(0)
B
4

To make HTTP(read api) requests in Tauri app you should use @tauri-apps/api/http module.

EXAMPLE:

npm install -D @tauri-apps/api

In tauri.conf.json file make sure you have this:

{
  "tauri": {
    "allowlist": {
      "http": {
        "all": true, // enable all http APIs. needed.
        "request": true, // enables only HTTP request API. optional
        "scope": ["https://localhost/*", "https://something.else/*"] // optional
      }
    }
  }
}

More can be found in the official docs.

Disclaimer: JSON standard does not allow comments.

Next, in your sample.ts file:

import {Body, fetch, ResponseType} from "@tauri-apps/api/http"

function apiRequest(data: FormData) {
  let body = Body.form(data);
  let response = await fetch(API_URL, {
    method: "POST",
    body: body,
    timeout: 30, //seconds
    responseType: ResponseType.JSON,
    // headers: {key: 'val'} // if needed
  });
  
  console.log(response.data);
}

This way you don't have to worry about CORS at all.

Thanks, @Vinay Rawat, & official docs.

I hope this helps someone.

Buckwheat answered 21/11, 2023 at 5:25 Comment(1)
will this work with vanilla?Extraversion

© 2022 - 2024 — McMap. All rights reserved.