DEV Community

bosemian
bosemian

Posted on

Avoid CORS in Nuxt.js with @nuxt/proxy

In a modern web application, we separated between front-end and back-end for flexible work. But CORS always happened on development if you don't know about CORS, please check Cross-Origin Resource Sharing

In this case, we gonna take look '@nuxt/proxy' module to avoid CORS.

Let's start !

I assume you already have a nuxt.js project then you just install '@nuxt/proxy'

npm i @nuxt/proxy
or
yarn add @nuxt/proxy

Add @nuxt/proxy to moduless in nuxt.config.js

{
  modules: [
    '@nuxtjs/proxy'
  ]
}

then add key you want to be a proxy like this

{
  proxy: {
  '/api/v1': { target: 'API_URL', pathRewrite: {'^/api/v1': ''} }
  }
}

now, when you call API you just add prefix to path in this case I'm gonna use axios to send request HTTP to my server like this

const PATH_API = '/service'
axios.get(`/api/v1${PATH_API}`);

Done !!

If I missed anything, please let me know Thank you :)

Top comments (2)

Collapse
 
definitelymaybe profile image
definitelymaybe

i believe its @nuxtjs/proxy, not @nuxt/proxy

Collapse
 
cesarbhering profile image
Cesar Bhering

How can i get this work on production ?