Nginx addresses cross domain issues when forwarding addresses

  • 2020-05-12 06:57:34
  • OfStack

1. What is a cross-domain problem

The json file was placed on one server A, and an error occurred when another server B tried to send an ajax request to A.

Chrome tip:


XMLHttpRequest cannot load ******. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

This is the cross-domain problem. There are a number of solutions. A better one is to configure CORS on the server side, but require changes on the server side. What if it is resolved without the need to change the server side? Especially if you need to test it locally.

2. Configuration Nginx

Open the conf folder in the nginx directory. Open nginx.conf and change the http request to:


http {
  include mime.types;
  server {
    listen    80;
    server_name localhost;
    charset UTF-8;

  location / {
    root html;
    index index.html index.htm;
  }

    # Avoid CORS and reverse proxy settings
    location /api/ { # [2]
      proxy_http_version 1.1;
      proxy_pass http://www.des.com/; # [3]

      add_header Access-Control-Allow-Origin *;
      add_header Access-Control-Allow-Methods "POST, GET, OPTIONS";
      add_header Access-Control-Allow-Headers "Origin, Authorization, Accept";
      add_header Access-Control-Allow-Credentials true;
    }
  }
}

Attention to the bold, when the request/api/said api directory to http: / / www des. com/domain name.

For example, request:

http: / / 127.0.0.1 / api/will turn http: / / www des. com /

http: / / 127.0.0.1 / api/aaa bbb/would turn http: / / www des. com/aaa bbb /

This kind of request forwarded by the server can break the cross-domain limit, so ajax can also work properly.

Note: /api/ cannot be written as /api.

http: / / www. des. com/nor written http: / / www des. com

3. The configuration hosts

To make native testing look more like testing on the target server, you can set up the system's hosts file.

Every system (windows, Linux, Mac OS) has the hosts file, which is the local domain name parser.

Usually, when we request a domain name, such as www.baidu.com, we first request baidu's IP address from the domain name server and then access it according to the IP address.

You can also enter baidu's IP address directly at local hosts without consulting the domain name server.

For example,

252.192.0.15 www.baidu.com

This way, the system will search for the IP address from the hosts file.

The hosts file under Windows is located at: C:\Windows\System32\drivers\etc

Open and add


127.0.0.1 www.des.com

Each time you visit www.des.com, you link to the local.

conclusion

The above is the whole content of this article, I hope the content of this article to your study or work can bring 1 definite help, if you have questions you can leave a message to communicate.


Related articles: