The problem of cross-domain requests is a very common problem with many solutions. The focus here is on configuring Nginx to implement cross-domain requests.

The principle of

The browser same-origin policy is designed to protect users from simple hacking. Do a cross-domain rule search. Lots of answers. The Nginx cross-domain scheme described today uses Nginx’s reverse proxy to trick the browser into thinking it is calling from the same source.

plan

Let’s assume that the application’s domain name is AAAA and requests the interface service provided on BBBB. The URL of the service on BBBB is BBBB/API. At this point, we make an AAAA/API request on aAAA, intercept the request with nginx and send it to BBBB/API. Complete the request process.

code

Ajax requests (URL only)

get(url, options) {
    return Q.Promise((resolve, reject) = > {
      ajax('aaaa/api'.'get', options)
        .then((data) = >{ resolve(data); }, (error) => { reject(error); }); })}Copy the code

Nginx configuration

location ~ ^/api {
  proxy_pass http://bbbb;
  proxy_redirect          off; 
  proxy_set_header        X-Real-IP       $remote_addr; 
  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for; 
}
Copy the code

advantages

  • Excellent compatibility, can be used in all browsers
  • Low cost, no additional server configuration, no front-end code modifications
  • Saves server performance
  • It can carry sessions without additional authentication information such as cookies