How to solve the front end cross domain problem with Nginx

  • 2020-05-15 03:40:20
  • OfStack


When developing static pages, like Vue, we often call interfaces that are most likely cross-domain, and then the browser will report cross-origin issues.

The easiest solution is to set the browser to ignore the security issue and set -- disable-web-security. This is a good way to develop PC pages, but not mobile pages.

The solution

Forward the request using Nginx. Write the cross-domain interfaces as interfaces to the callback domain, and forward those interfaces to the actual request address.

Take a chestnut

For example, we are developing an Vue application.

The original:

Debug page is: http: / / /

Request of interface is: http: / / ni hao. sao/api/get/info

Step 1:

Request of interface is: http: / / / api get/info

PS: this solves the cross-domain problem.

Step 2:

After installed Nginx, go to/usr/local etc/nginx/directory (this is Mac), modified nginx. conf file.

Step 3:

Comment out the default server configuration.

Add below:

    listen 8888;
    location /{
    location /api{
      proxy_pass http://ni.hao.sao/api;

After saving, launch Nginx.

PS: you don't need to know much about the configuration of Nginx, it's very simple.

Step 4:

Access: http: / / /

Get things done.

PS: note that the port you are accessing is' 8888', just add location to any other domain address.

Error model

I did not understand the configuration of Nginx at the beginning of 1, thinking that it could be configured as follows.

    listen 8080;
    location /api{
      proxy_pass http://ni.hao.sao/api;

I wrote it this way because I thought it would allow Nginx to listen for 8080 requests and forward only the matching requests. What I didn't realize was that after Nginx was written this way, it would take up port 8080.

Since the port needs to be occupied, it can no longer be occupied by other processes of the same protocol, resulting in pages that are developed that cannot be enabled on port 8080. By the colleague to raise point, just think of this thing, change the train of thought, had the most top method.


You can do this not only in development and debugging, but in production as well. By forwarding the request using Nginx, you can eliminate the need for the static page to be deployed to be in the same domain as the request interface.

Related articles: