已解决:No ‘Access-Control-Allow-Origin‘ header is present on the requested resource
Table of contents
1.Problem description
The front-end is vue, and the back-end is springcloud. It is a completely separate project between the front and back ends. When the front end sends a request to the back end, the following error occurs. No 'Access-Control-Allow-Origin' header is present on the requested resource.
2.Solution process
Analysis: When we request an interface, words such as Access-Control-Allow-Origin appear, indicating that the request is cross-domain. So what is cross-domain?
All browsers that use JavaScript will support the same-origin policy. The same origin policy means that the domain name/protocol/port number are the same. As long as there is one difference, it will be regarded as a cross-domain request.
Option 1: Configure the backend interface as follows:
Option 2: You can set up a proxy on the front end
Create a new file in the project root directory vue.config.js
and add configurations in the file
module.exports = {
devServer: {
proxy: {
'/test': {
target: 'https://baidu.com',
ws: true,
changeOrigin: true,
pathRewrite: {
'^/test': '' //遇到接口路径有test的,就换成http://www.baidu.com/这个请求头,同时把test去掉
}
}
}
},
}
I record the problems I encountered at work and the process of solving them, and I hope it can help everyone!