skip to Main Content

In my local environment I’m trying to reach the development server which is in https://api.mydomain.com

When I made the call from my nextjs/reactjs app I get CORS error, so I try to fix it with reverse proxy on next in the following way:

/** @type {import('next').NextConfig} */
const nextConfig = {
  experimental: {
    appDir: true,
  },
  async rewrites() {
    return [{
      source: "/api/:path*",
      destination: "https://api.mydomain.com/:path*",
    }]
  }
}

module.exports = nextConfig

And in the app I’m calling the backend in the following way:

const login = async (user: any) => {
    const data = await fetch("/api/v1/auth/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(user),
    });
    return data;
  };

As the result I get a 404 error, but without any body. So it seems that it’s not reaaching the server.

POST http://localhost:3000/api/v1/auth/login net::ERR_ABORTED 404 (Not Found)

But If I call directly the server to the following url, it works fine https://api.mydomain.com/v1/auth/login it works

2

Answers


  1. I got the same problem, You can solve this by 2 methods:-

    1st Check the CORS Options that you are set in your backend. If you are not allowed the option that you are using please allow it. For example, in NodeJs

    enter image description here

    2nd Its Also occurs when your backend & frontend are hosted on the same server and you are calling your backend from serverside with the domain name. In that case, you have to use localhost instead of the domain and the problem will solve. For example, I made two variables in my .env file

    DOMAIN_API_URL=https://api.mydomain.com

    SERVER_SIDE_API_URL=http://localhost:4000

    Note:- If you are still getting the 404 issues then it is not the issue of CORS. You have to check, your frontend is not able to find any apis or not able to trigger the correct URL.

    Login or Signup to reply.
  2. You are missing the complete url on your fetch

    const data = await fetch("https://api.mydomain.com/v1/auth/login"
    

    you get that error because it thinks you try to fetch from you localhost

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search