Home > Net >  How to fix blocked by CORS policy error from Vue2 and axios
How to fix blocked by CORS policy error from Vue2 and axios

Time:04-19

I have a Vue app with axios and I need to make login call to api, but I get this error:

Access to XMLHttpRequest at 'https://api.test.com/login/' from origin 'http://localhost:8080' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

I tried everything that I found and I think my vue.config.js is not working properly. Here is the last version I tried:

module.exports = {
  devServer: {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': 'true',
      'Access-Control-Allow-Methods': 'GET,HEAD,OPTIONS,POST,PUT',
      'Access-Control-Allow-Headers':
        'Origin, X-Requested-With, Content-Type, Accept, Authorization',
    },
    proxy: 'https://api.test.com/',
  },
}

I put the headers there to check if the request get them, but it has no headers, so I suppose the config file is not working? My axios looks like this:

import axios from 'axios'
axios.defaults.baseURL = 'https://api.test.com/'
export default axios

And finally my package json is this:

{
  "name": "vue",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "@googlemaps/markerclusterer": "^2.0.1",
    "@googlemaps/ogc": "^1.0.21",
    "axios": "^0.26.0",
    "bootstrap": "^5.1.3",
    "bootstrap-vue": "^2.21.2",
    "core-js": "^3.8.3",
    "gsap": "^3.9.1",
    "material-design-icons-iconfont": "^6.6.0",
    "md5": "^2.3.0",
    "proj4": "^2.8.0",
    "vue": "^2.6.14",
    "vue-axios-cors": "^1.0.1",
    "vue-router": "^3.5.1",
    "vue-screen": "^1.5.6",
    "vue2-google-maps": "^0.10.7",
    "vuex": "^3.6.2"
  },
  "devDependencies": {
    "@babel/core": "^7.12.16",
    "@babel/eslint-parser": "^7.12.16",
    "@vue/cli-plugin-babel": "~5.0.0",
    "@vue/cli-plugin-eslint": "~5.0.0",
    "@vue/cli-plugin-router": "~5.0.0",
    "@vue/cli-plugin-vuex": "~5.0.0",
    "@vue/cli-service": "~5.0.0",
    "eslint": "^7.32.0",
    "eslint-config-prettier": "^8.3.0",
    "eslint-plugin-prettier": "^4.0.0",
    "eslint-plugin-vue": "^8.0.3",
    "prettier": "^2.4.1",
    "vue-template-compiler": "^2.6.14"
  }
}

My ultimate goal is to jump through this CORS error and be able to make requests to this api, if anyone can suggest something I will be very grateful!

CodePudding user response:

I finally managed to fix it, so for everyone that have this problem using axios, here is the solution. The problem was in this code:

axios.defaults.baseURL = 'https://api.test.com/'

Removing it make the vue.config.js proxy to work. Now everything works as expected.

  • Related