In vue, because the reverse proxy can hide the real server and bypass the cross-domain problem caused by directly requesting the real URL, it is necessary to use a reverse proxy to avoid cross-domain problems; reverse proxy It is often used in scenarios where front-end and back-end are developed separately. The front-end needs to connect to the back-end interface and send requests from the same source to the reverse proxy server.
The operating environment of this article: Windows 10 system, Vue version 2.9.6, DELL G3 computer.
Reverse proxy usage scenario
In the scenario of separate development of front-end and back-end, there is a server in the front-end (provided Static page), the backend has a server (providing an interface)
At this time, the frontend needs to connect to the backend interface, and cross-domain problems will occur
In the release environment, if there is a cross-domain Problem, use nginx
If the front-end and back-end codes are on the same server, there is no cross-domain problem
Cross-domain solution
jsonp (front-end solution Solution)
CORS (back-end solution): cross origin resource sharing
Reverse proxy (front-end solution)
What is a reverse proxy
Reverse proxy hides the real server, so that the browser is still from the same origin
Reverse proxy principle
By forging requests to make http The request is from the same source, and then the request from the same source is sent to the reverse proxy server, and the reverse proxy server requests the real URL, thus bypassing the cross-domain problems caused by directly requesting the real URL
Configuration of reverse proxy
Reverse proxy of vue-cli3
Create a new vue.config.js file in the project root directory
Configuration Code:
module.exports = {undefined lintOnSave:false, devServer:{undefined proxy: { '/api': { target: 'http://localhost:80', changeOrigin: true, pathRewrite: {undefined '^/api': "" }, '/apidouban': {undefined target: 'http://localhost:3001', changeOrigin: true, pathRewrite: {undefined '^/apidouban': "" } } } } }
Reverse proxy execution process:
Convert /api in axios access address to target /api:
(eg: http:localhost:9000/api /goods is converted to http://localhost:80/api/goods)
Create a virtual server
Remove /api:
(eg: http://localhost: 80/goods)
[Related recommendations: "vue.js tutorial"]
The above is the detailed content of Why use Vue's reverse proxy?. For more information, please follow other related articles on the PHP Chinese website!