Nuxt.js — How to handle CORS error

answer: routeRules

Soo Kim
2 min readApr 18, 2023

Yesterday, I started playing around with Nuxt.js but for several hours had a difficult time connecting my Nuxt.js app on port 3000 to my server on local host (port 9300). After almost a whole day of futile efforts, I finally found a solution and maybe someone might find it helpful :) I’ll post the solution first for anyone who wants a quick answer, and then I’ll go through steps I took to reach the answer.

Here’s the final code:

// notice that its 127.0.0.1 and not localhost
// port number is your nuxt.js

const _res = await axios.get("http://127.0.0.1:3000/web/v1/stores?page=1&pageSize=16");

// nuxt.config.ts
export default defineNuxtConfig((){
routeRules: {
'/web/v1/**': {
proxy: { to: "http://127.0.0.1:9300/web/v1/**", },
}
}
})

Steps Taken

Connect Directly to localhost:9300

If you try to just fetch directly from the server url like below, CORS policy prevents the request from going through.

const _res = await axios.get("http://localhost:9300/web/v1/stores?page=1&pageSize=16", {
headers: { "Access-Control-Allow-Origin": "*", 'Access-Control-Allow-Headers': '*', },
});
CORS error

Set Nitro devProxy

Then, I tried to set up a devProxy.

// nuxt.config.ts
export default defineNuxtConfig((){
nitro: {
devProxy: {
"/web": {
target: "http://localhost:9300",
Headers: { "Access-Control-Allow-Origin": "*", 'Access-Control-Allow-Headers': '*', },
prependPath: true,
changeOrigin: true,
},
}
}
})

This time, a TCP connection error occurred.

According to this github thread, Node 17 had a breaking change with how DNS.lookup works: instead of ignoring your OS configuration and re-sorting IP address lookups, it returns them as-is. In my case, my server listens to the IPv4 address (127.0.0.1) but node 17 was returning IPv6 of localhost (::1).

So, I switched localhost to 127.0.0.1.

But…although the TCP connection error disappeared, now the erro was that the page couldn’t be found (404).

Set routeRules

Thanks to this github thread, I found the solution: set routeRules in nuxt.config.ts.

// nuxt.config.ts
export default defineNuxtConfig((){
routeRules: {
'/web/v1/**': {
proxy: { to: "http://localhost:9300/web/v1/**", },
}
}
})

I’m still not sure I completely understand the reason for the errors…but I’m just glad I was able to find the solution before I went crazy.

--

--