How to Solve CORS Errors with Nuxt.js + axios

Tadashi Shigeoka ·  Thu, May 20, 2021

I’ll introduce how to solve CORS errors when using axios with Nuxt.js.

Nuxt.js

Background: Access to XMLHttpRequest at xxx has been blocked by CORS policy

An error like “Access to XMLHttpRequest at ‘http://localhost:3000/api/me’ from origin ‘http://localhost:3001’ 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.” occurred with Nuxt.js + axios.

Solution: Resolve with axios option proxy: true

I wasn’t specifying the axios option proxy: true in nuxt.config.js, so when I added it, the problem was resolved.

  axios: {
    proxy: true
  },

Correct Way to Write nuxt.config.js

nuxt.config.js

{
  modules: [
    '@nuxtjs/axios'
  ],

  axios: {
    proxy: true
  },

  proxy: {
    '/api/': { target: 'http://localhost:3000', pathRewrite: {'^/api/': ''} }
  }
}

That’s all from the Gemba about solving CORS errors with Nuxt.js + axios.

Reference Information