Anil Kumar
Anil Kumar

Reputation: 41

In nuxt.js getting CORS problem No 'Access-Control-Allow-Origin' header is present on the requested resource

I am doing authentication register in nuxt.js with laravel8 backend when submit its getting error like this... Access to XMLHttpRequest at 'http://127.0.0.1:8000/api' from origin 'http://localhost:3000' 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.

how to solve this,

register.vue

 methods: {
   onSubmit(){
     this.$axios.$post("http://127.0.0.1:8000/api", {
       email: this.email,
       password: this.password,
       name: this.name,
       returnSecureToken: true,
     } ,
     ).then(result => {
       console.log(result)
     })
     .catch(e => console.log(e));
   }
  }

nuxtConfig.js

modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    '@nuxtjs/auth',
    '@nuxtjs/proxy'
  ],

  proxy: {
    '/api': {
      target: 'http://127.0.0.1:8000',
      changeOrigin: true,
      pathRewrite: { '^/api': '/' },
    },
  },
  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {
    baseURL: "https://127.0.0.1:8000/api",
    proxy: true,
    credentials: false
  },

Upvotes: 0

Views: 17263

Answers (1)

Vishal Sagar
Vishal Sagar

Reputation: 391

In nuxt.config.js turn proxy: true and add proxy which will be used while calling like this:

axios: {
    proxy: true
  },
proxy: {
    "/api": "https://127.0.0.1:8000"
  },

Than while calling the API just use "/api" it will append the prefix

 methods: {
   onSubmit(){
     this.$axios.$post("/api", {
       email: this.email,
       password: this.password,
       name: this.name,
       returnSecureToken: true,
     } ,
     ).then(result => {
       console.log(result)
     })
     .catch(e => console.log(e));
   }
  }

Nuxt Link

Upvotes: 1

Related Questions