Access to XMLHttpRequest at 'https://***' from origin 'http://localhost:3000' has been blocked by CORS policy

Viewed 1004

I'm trying to send a request with axios but I have CORS problem, this is my nuxt.config.js

plugins: [
"@/plugins/axios/apiService.js",
],
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy',
  ],
  
  axios: {
    baseURL: process.env.API_URL,
    proxy: true,
    credentials: false
  },
  proxy: {
    '/api': {
      target: 'https://dev.mobit.ir/api/web/v4',
      pathRewrite: {
        '^/api' : '/'
        },
      changeOrigin: true,
      }
  },

and this is my apiService

import axios from "axios";
import { API_URL} from "./config";

export const axiosInstance = axios.create({
  headers: {
    Accept: 'application/json',
  }
});

//Set base url for axios requests
axiosInstance.defaults.baseURL = API_URL;

export const ApiService = {
  
  //resource: api address
  get(resource, params = "") {
    return axiosInstance.get(resource, {params}).catch(error => {
      throw new Error(`[RWV] ApiService ${error}`);
    });
  },

  post(resource, params) {
    return axiosInstance.post(`${resource}`, params);
  }
};

I tried to set proxy according to nuxt documentation but it doesn't work, If I use a proxy like https://cors-anywhere.herokuapp.com/ it will works but what why nuxt proxy doesn't work? and I think it's not the correct way. Do I have to use cookie or middleware?

2 Answers

according to the link below, we should use an array in our module's array for defining proxy like this:

['@nuxtjs/proxy', { pathRewrite: { '^/api' : '/api/web/v4' } }]

link to read more: https://github.com/nuxt-community/proxy-module

Related