如何修复 Vue2 和 axios 中被 CORS 策略错误阻止的问题

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

我有一个带有 axios 的 Vue 应用程序,我需要对 api 进行登录调用,但我收到此错误:

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.

我尝试了所有发现的方法,但我认为我的 vue.config.js 无法正常工作。这是我试过的最后一个版本:

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/',
  },
}

我把 headers 放在那里检查请求是否得到它们,但它没有 headers,所以我想配置文件不起作用? 我的 axios 看起来像这样:

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

最后我的包裹 json 是这样的:

{
  "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"
  }
}

我的最终目标是跳过这个 CORS 错误并能够对此 api 提出请求,如果有人能提出建议,我将不胜感激!

我终于设法修复了它,所以对于使用 axios 遇到此问题的每个人,这里是解决方案。问题出在这段代码中:

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

删除它会使 vue.config.js 代理工作。现在一切正常。