Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS issue on version 0.14.0 #1218

Closed
bendo01 opened this issue Jan 25, 2025 · 8 comments
Closed

CORS issue on version 0.14.0 #1218

bendo01 opened this issue Jan 25, 2025 · 8 comments

Comments

@bendo01
Copy link

bendo01 commented Jan 25, 2025

Description

i'm installing loco using loco cli generator but cors policy still block request from client app

To Reproduce

❯ loco new
✔ ❯ App name? · locofreshinstall
✔ ❯ What would you like to build? · Rest API (with DB and user auth)
✔ ❯ Select a DB Provider · Postgres
✔ ❯ Select your background worker type · Queue (standalone workers using Redis)

check using loco doctor

❯ cargo loco doctor
Finished dev profile [unoptimized + debuginfo] target(s) in 0.67s
Running target/debug/locofreshinstall-cli doctor
2025-01-25T03:30:48.276412Z DEBUG app: loco_rs::bgworker: job queue ping requested environment=development
✅ SeaORM CLI is installed
✅ DB connection: success
✅ redis queue: queue connection: success
✅ Dependencies
✅ Loco version: latest

cargo loco middleware --config
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.59s
     Running `target/debug/locofreshinstall-cli middleware --config`
2025-01-25T03:31:30.746789Z  WARN app: loco_rs::boot: pretty backtraces are enabled (this is great for development but has a runtime cost for production. disable with `logger.pretty_backtrace` in your config yaml) environment=development
limit_payload          {"body_limit":{"Limit":2000000}}
catch_panic            {"enable":true}
etag                   {"enable":true}
logger                 {"config":{"enable":true},"environment":"development"}
request_id             {"enable":true}
fallback               {"code":200,"enable":true,"file":null,"not_found":null}
powered_by             {"ident":"loco.rs"}


cors                   (disabled)
remote_ip              (disabled)
compression            (disabled)
timeout_request        (disabled)
static                 (disabled)
secure_headers         (disabled)

cargo toml

[workspace]

[package]
name = "locofreshinstall"
version = "0.1.0"
edition = "2021"
publish = false
default-run = "locofreshinstall-cli"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[workspace.dependencies]
loco-rs = { version = "0.14.0" }

[dependencies]
loco-rs = { workspace = true  }
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1" }
tokio = { version = "1.33.0", default-features = false, features = [
  "rt-multi-thread",
] }
async-trait = { version = "0.1.74" }
axum = { version = "0.8.1" }
tracing = { version = "0.1.40" }
tracing-subscriber = { version = "0.3.17", features = ["env-filter", "json"] }
regex = { version = "1.11.1" }
migration = { path = "migration" }
sea-orm = { version = "1.1.0", features = [
  "sqlx-sqlite",
  "sqlx-postgres",
  "runtime-tokio-rustls",
  "macros",
] }
chrono = { version = "0.4" }
validator = { version = "0.19" }
uuid = { version = "1.6.0", features = ["v4"] }
include_dir = { version = "0.7" }

[[bin]]
name = "locofreshinstall-cli"
path = "src/bin/main.rs"
required-features = []

[dev-dependencies]
loco-rs = { workspace = true, features = ["testing"] }
serial_test = { version = "3.1.1" }
rstest = { version = "0.21.0" }
insta = { version = "1.34.0", features = ["redactions", "yaml", "filters"] }

i'm using SolidStart template

here is my typescript snipped code

const handleSubmit = async (event: SubmitEvent) => {
    event.preventDefault();
    console.log(JSON.stringify(form));
    try {
      const server_api_url = import.meta.env.VITE_API_SERVER_URL ?? 'http://localhost:5150/api';
      const response = await fetch(`${server_api_url}/auth/login`, {
        method: "POST", // HTTP method
        headers: {
          "Content-Type": "application/json", // Specify the data format
          "Accept": "application/json",
          "Access-Control-Allow-Origin": "*"
        },
        body: JSON.stringify(form), // Send form data as JSON
      });
      console.log(response.status);
      if (!response.ok) {
        // biome-ignore lint/style/useTemplate: <explanation>
        throw new Error("Failed to submit form: " + response.statusText);
      }

      const data = await response.json();
      console.log("Success:", data);

      // Optionally handle the response data, such as redirecting
      // window.location.href = "/dashboard";
    } catch (error) {
      console.error("Error:", error);
    }
  };

here is error message from browsers console

Access to fetch at 'http://localhost:5150/api/auth/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.
index.tsx:33 
        
        
       POST http://localhost:5150/api/auth/login net::ERR_FAILED

here is error from loco cli

environment: development
   database: automigrate
     logger: debug
compilation: debug
      modes: server

listening on http://localhost:5150
2025-01-25T04:00:22.546115Z DEBUG http-request: tower_http::trace::on_request: started processing request http.method=OPTIONS http.uri=/api/auth/login http.version=HTTP/1.1 http.user_agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 environment=development request_id=fa4cf1d5-af08-43dc-9824-9378e1d4e74e
2025-01-25T04:00:22.546699Z DEBUG http-request: tower_http::trace::on_response: finished processing request latency=0 ms status=405 http.method=OPTIONS http.uri=/api/auth/login http.version=HTTP/1.1 http.user_agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 environment=development request_id=fa4cf1d5-af08-43dc-9824-9378e1d4e74e

Environment:
Operating System : OSX Sonoma 14.2.1 (23C71)

❯ rustc --version
rustc 1.84.0 (9fc6b4312 2025-01-07)

is anyone has this kind of problem using loco 0.14.0 ?

@kaplanelad
Copy link
Contributor

Why are you including "Access-Control-Allow-Origin": "*" in your JavaScript request headers if CORS is not being used?
Can you remove it to see if it resolves the issue?

@bendo01
Copy link
Author

bendo01 commented Jan 26, 2025

this is my updated typescript snipped code

const handleSubmit = async (event: SubmitEvent) => {
    event.preventDefault();
    console.log(JSON.stringify(form));
    try {
      const server_api_url = import.meta.env.VITE_API_SERVER_URL ?? 'http://localhost:5150/api';
      const response = await fetch(`${server_api_url}/auth/login`, {
        method: "POST", // HTTP method
        headers: {
          "Content-Type": "application/json", // Specify the data format
          "Accept": "application/json"
        },
        body: JSON.stringify(form), // Send form data as JSON
      });
      console.log(response.status);
      if (!response.ok) {
        // biome-ignore lint/style/useTemplate: <explanation>
        throw new Error("Failed to submit form: " + response.statusText);
      }

      const data = await response.json();
      console.log("Success:", data);

      // Optionally handle the response data, such as redirecting
      // window.location.href = "/dashboard";
    } catch (error) {
      console.error("Error:", error);
    }
  };

this is the output from browsers console

Access to fetch at 'http://localhost:5150/api/auth/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

this is the output from loco cli

2025-01-26T19:37:16.223001Z DEBUG http-request: tower_http::trace::on_request: started processing request http.method=OPTIONS http.uri=/api/auth/login http.version=HTTP/1.1 http.user_agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 environment=development request_id=2a3b2acf-d21f-489b-bf71-c490e08799cd
2025-01-26T19:37:16.223536Z DEBUG http-request: tower_http::trace::on_response: finished processing request latency=0 ms status=405 http.method=OPTIONS http.uri=/api/auth/login http.version=HTTP/1.1 http.user_agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 environment=development request_id=2a3b2acf-d21f-489b-bf71-c490e08799cd

still the problem on OPTIONS (prelight) request.

@kaplanelad
Copy link
Contributor

do you have example repo to share?

@bendo01
Copy link
Author

bendo01 commented Jan 26, 2025

this is the repo, thank you for taking look at it

https://github.com/bendo01/locofreshinstall

@kaplanelad
Copy link
Contributor

I do not see the frontend part. Can you add it?

@bendo01
Copy link
Author

bendo01 commented Jan 27, 2025

this is client app repo

https://github.com/bendo01/client_app

i've create login form on src/routes.index.tsx

this is .env that i use

COMPATIBILITY_DATE=2025-01-13
VITE_API_SERVER_URL="http://localhost:5150/api"

@kaplanelad
Copy link
Contributor

CORS determines whether resources can be accessed across different origins (e.g., different ports, domains, or protocols).
When working with two different endpoints (e.g., different ports), browsers block requests due to security policies unless the server explicitly allows them via CORS headers.

You have two options to resolve this:

Option 1: Set up a client proxy with Vite

Create a vite.config.js file with the following content:

import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

// https://vitejs.dev/config/
export default defineConfig({
    plugins: [react()],
    server: {
        proxy: {
            "/api": {
                target: "http://127.0.0.1:5150",
                changeOrigin: true,
                secure: false,
            },
        },
    },
})

And update the following line in your code:
Replace this

const server_api_url = import.meta.env.VITE_API_SERVER_URL ?? 'http://localhost:5150/api';

with this

const server_api_url = import.meta.env.VITE_API_SERVER_URL ?? 'api';

Option 2: Enable middleware

If you prefer not to use a proxy, you can enable middleware in your server. Add the following configuration:

middlewares:
  cors:
    enable: true
    allow_origins:
      - '*'

Both solutions should work for your scenario. Choose the one that best fits your setup.

@bendo01
Copy link
Author

bendo01 commented Jan 27, 2025

implement your solution both on option 1 and option 2, your solutions work

thank you for taking your time and give solution that works, i hope your solution benefit others who come with same problem

best regards

@bendo01 bendo01 closed this as completed Jan 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants