Modern front-end development mode: Use Node to start local services, and then directly access debugging via localhost or 127.0.0.1. This is how most front-end development works every day, and for the most part, there’s nothing wrong with it. However, for some special scenarios, such as the wechat public account or the Nail H5 micro application, which need to be embedded in the third-party platform for debugging, the direct use of localhost local domain name will be restricted. At this time, we need to use the real domain name to access our local services.
Using forward proxy
Take Charles as an example to illustrate how to use a forward proxy to forward requests corresponding to domain names to local services.
Start by opening Charles’ HTTP proxy service:
Then, open the Map Remote agent:
Then add the corresponding proxy forwarding rule to forward the target domain name to the specified port of the local service:
Finally, point the browser’s proxy to the local Charles service:
This way, when we visit http://www.demo.com, we are forwarded directly to the local service http://localhost:8082.
Using a Reverse proxy
In addition to forward proxy, we can also use modified hosts file + nginx reverse proxy to achieve.
First, forward the request for the target domain name locally by modifying the hosts file:
127.0.0.1 www.demo.com
Copy the code
Since the hosts file does not support port forwarding, we also need to start the nginx service locally, listen on port 80 and reverse proxy to the local Node service:
server { listen 80; server_name *.demo.com; location / { proxy_pass http://localhost:8082/; proxy_set_header Host localhost; proxy_set_header Origin localhost; proxy_hide_header Access-Control-Allow-Origin; add_header Access-Control-Allow-Origin "http://www.demo.com"; } location /sockjs-node/ { proxy_pass http://localhost:8082; proxy_set_header Host localhost; proxy_set_header Origin localhost; Proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_hide_header Access-Control-Allow-Origin; add_header Access-Control-Allow-Origin "http://www.demo.com"; }}Copy the code
The /sockjs-node/ configuration is used for hot reload.
After the configuration, use nginx -s reload to restart the service, and when you visit http://www.demo.com again, you will get the contents of the local service http://localhost:8082.
If an error message is displayed indicating that the user has no permission, run the following command to resolve the problem:
sudo nginx -s stop
sudo chmod -R 777 /usr/local/var/run/nginx/*
Copy the code
This is because scripts in development mode are not compressed and the files are large, and Nginx caches large files locally to speed them up. If you do not have write permission to the local directory, an error message will be thrown.
Reference:
- VueJS dev serve with reverse proxy
- How does front-end development solve cross-domain problems independently
- Hosts file and domain name resolution