问题描述
基于Vue3和SpringBoot进行前后端分离开发,实现登录功能。在测试提交表单时axios报错。
前端报错信息:
Uncaught runtime errors:
ERROR
Network Error
AxiosError: Network Error
at XMLHttpRequest.handleError (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:155:14
浏览器控制台报错:
Access to XMLHttpRequest at 'http://localhost:8088/api/admin/login' from origin 'http://localhost:8080' 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.
原因分析
这个错误是由于浏览器的跨域安全策略导致的。浏览器限制了跨域请求,只有在服务端设置了响应头 Access-Control-Allow-Origin 时,才允许跨域请求。
解决方案
修改前端配置
- 修改 vue.config.js
const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
transpileDependencies: true,
devServer: {
proxy: {
'/api': {
target: 'http://localhost:8088',
changeOrigin: true,
pathRewrite: {
'/api': ''
}
}
}
}
})
其中 http://localhost:8088 为后端服务器地址。
通过代理请求转发到后端服务器,从而避免了跨域问题。
- 在 src/main.js 中添加:
axios.defaults.baseURL = '/api'
让 axios 的请求默认发送到代理服务器上,这样在开发过程中就不需要手动修改请求地址。
注意: 修改完成后需要重新启动vue-cli-service serve,否则会报404。