Use nginx as a reverse proxy to solve front-end cross-domain problems

Recently, a friend raised a question in the group. Their company provided him with an interface to obtain data. Accessing this interface in the browser can obtain json data, but using ajax in the project will cause cross-domain problems. Generally, this The backend that needs to provide the interface needs to do cross-domain processing, but the interface is not provided by their company, and then I ask everyone if there is a solution.

I just read some knowledge about node in the past few days. I told him that you can make your backend do an interface forwarding, use your backend to request this interface, and then provide an interface for you to use, which is equivalent to doing There is a transfer, because there is no cross-domain between servers, so data can be requested.

Then he asked if there was another solution. I felt that this was a bit troublesome. Then I thought about it carefully, and suddenly I remembered the way nginx solves cross-domain, but I can't remember it clearly, so I searched for related problems and gave them online. There is a lot of information, in fact, the implementation is very simple, that is to use nginx as a reverse proxy, but this requires the assistance of background personnel. Specific steps:

1. Find the server{} in the nginx.conf file on the server where nginx is installed. If it is not found, go to the default.conf file in the conf.d folder at the same level of the file.

2. Add the following code in it

server
{
    listen 80;
    server_name www.aaa.top;
    location / {
        proxy_pass http://www.bbb.com;
        add_header 'Access-Control-Allow-Origin' '*';  
        add_header 'Access-Control-Allow-Credentials' 'true';  
    }
    ##### other directive
}

  Among them, www.aaa.com represents your own domain name, and www.bbb.com represents someone else's domain name, which is the domain name that needs to be cross-domain, then add the request header that allows cross-domain, and then restart nginx.

In this case, requesting the interface of www.aaa.com is equivalent to requesting the interface of www.bbb.com.

The above is the use of nginx as a reverse proxy to solve cross-domain solutions.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325201691&siteId=291194637