1. Personal confusion
When I was faced with cross-domain problems for the first time, as a technical novice, I was confused when I saw the solutions of online giants. However, with in-depth understanding and consulting the configuration documents of Webpack, I got a preliminary understanding and ideas on how proxy proxy can solve cross-domain problems. The following are my personal analysis ideas.
2. How is cross-domain generated?
Server: http://localhost:8080
Client: http://localhost:3000
Personal opinion:
Cross-domain is caused by the fact that the server and the client are on different servers. When we want to request the content of the server through the client, we are affected by the same origin policy of the browser (the error description has been corrected). As a result, we can only receive requests from the same address as the server. In the preceding example, you can only receive requests from port 8080 and reject requests from port 3000.
3. Cross-domain solutions
The following cross-domain solutions have been learned from documents and big-name articles
The first method: Assuming that the Server is built for Express, express middleware is used to open the address of all request ports and request headers to solve cross-domain problems. However, this method has many problems and is not recommended.
let app = express();
app.use((req,res,next)=>{
res.append('Access-Control-Allow-Origin',"*")
res.append('ACcess-Control-Allow-headers',"*")
next()
})
Copy the code
Second: use webPack’s devServer.proxy configuration
In Vue2.6 version and before 2.6 version, are packaged by Webpack, so when using Vue framework to do front-end page, in order to improve the development efficiency, front-end temporary use of proxy proxy method in the development environment to solve cross-domain problems is very convenient.
Solution:
Create the Vue.config.js configuration file in the Vue project root directory
module.exports = {
devServer: {proxy: {'/api': {/ / access request by target pointing to http://localhost:8080/api
//http://localhost:3000/api
target:"http://localhost:3000".// Replace/API with null by path rewriting
pathRewrite: {'^/api':""
}
}
}
}
}
Copy the code