Problem Description
Based on Vue3 and SpringBoot, the front-end and back-end are developed separately to implement the login function. Axios reported an error when testing the form submission.
Front-end error message:
Uncaught runtime errors:
ERROR
Network Error
AxiosError: Network Error
at XMLHttpRequest.handleError (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:155:14
Browser console error:
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.
Cause Analysis
This error is caused by the browser's cross-origin security policy. The browser restricts cross-domain requests. Cross-domain requests are only allowed when the response header Access-Control-Allow-Origin is set on the server.
solution
Modify front-end configuration
- Modify 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': ''
}
}
}
}
})
Where http://localhost:8088 is the backend server address.
Forward requests to the backend server through a proxy, thus avoiding cross-domain issues.
- Add in src/main.js:
axios.defaults.baseURL = '/api'
Let axios requests be sent to the proxy server by default, so that there is no need to manually modify the request address during the development process.
Note: After the modification is completed, vue-cli-service serve needs to be restarted, otherwise 404 will be reported.