Search code examples
javascriptreactjsmongodbexpressmern

How to fix DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL MERN Stack


Hello I got this error after I deployed my app on Heroku. The frontend rendered just fine but I think somethings wrong with my backend side.

DOMException: Failed to execute 'open' on 'XMLHttpRequest': Invalid URL at https://recit-note-app.herokuapp.com/static/js/2.b7aa495c.chunk.js:2:87478 at new Promise () at e.exports (https://recit-note-app.herokuapp.com/static/js/2.b7aa495c.chunk.js:2:87186) at e.exports (https://recit-note-app.herokuapp.com/static/js/2.b7aa495c.chunk.js:2:249521)

Here's my Axios instance:

const instance = axios.create({
baseURL: `https://recit-note-app.herokuapp.com:${process.env.PORT}/api/`,
timeout: 5000,
headers: {
  "Content-Type": "application/json",
  accept: "application/json",
},
});

And one of my handlers to fetch user data:

try {
const response = await instance.get(`user`, {
  headers: {
    "x-access-token": token,
  },
});
const data = await response;
JSON.stringify("data");
return data;
} catch (error) {
  console.error(error);
  return error.response;
}

I dont know what caused the error. Do you guys know how to fix such error? Thank you.


Solution

  • I solved the problem. Turned out I do not need to set port to call the API, just need the url. So I just change the url to the web without port :).

    baseURL: `https://recit-note-app.herokuapp.com/api/`
    

    I encountered problem with CORS too so I added the url to CORS Origin. Refer to: https://www.npmjs.com/package/cors#configuration-options

    const corsOptions = {
      origin: ["http://localhost:3000", "https://recit-note-app.herokuapp.com/"],
    };