Use nginx to solve front-end cross-domain problems

Write server write interface to simulate backend

First of all, I wrote a server interface with node, on the premise that node.js is installed

npm init -y

npm i express

Create app.js


const express = require("express");
const app = express();
app.get("/getList", (req, res) => {
    res.send({
        status: 0,
        message: "请求成功",
        data: [
            { id: 1, name: "张三", age: 20 },
            { id: 2, name: "李四", age: 22 },
            { id: 3, name: "王五", age: 23 },
        ]
    })
})
app.listen(666, () => {
    console.log("http://localhost:666/getList");
})


node app.js runs successfully and the interface is created successfully

cross domain

The front-end creates index..html to run, initiates a request, and sees cross-domain

 

nginx implements cross-domain 

Reference blogger

Install the official website  nginx: download

start nginx

Unzip double-click nginx.exe 

Find the nginx decompression directory, right-click, find and git bashopen (if there is no git tool, open the command line to enter the current directory) and enter the command start ./nginx.exeEnter to start the nginx service.

Enter localhost and press Enter to see the figure below, the startup is successful 

Change setting

In the installation directory of nginx, find the conf/nginx.conf configuration and copy it directly

#user  nobody;
worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;


events {
    worker_connections  1024;
}


http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;
    server_names_hash_bucket_size 128;
    server {
        listen       80;
        server_name  localhost;
        location / {
            root   html;
            index  index.html index.htm;
        }
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

    server {
        listen       8888;
        server_name  test-local.test.com;
        # 这里是你要代理的测试环境域名加上-local
        # 比如你的项目测试环境为a.test.com,你本地此处可以设置为a-local.test.com,当然你可以随便设置
#这里说明了如果是http://test-local.test.com:8888/则说明跨域,用以下http://127.0.0.1:666/请求
        location /{
          add_header 'Access-Control-Allow-Origin' '*';
          add_header 'Access-Control-Allow-Credentials' 'true';
          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
          add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
          add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
          #proxy_pass 你要跨域的的接口地址
          proxy_pass    http://127.0.0.1:666/;
        }
#这里说明了如果是http://test-local.test.com:8888/api/则说明跨域,用以下http://127.0.0.1:666/请求
         location ^~/api/{
 add_header 'Access-Control-Allow-Origin' '*';
          add_header 'Access-Control-Allow-Credentials' 'true';
          add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
          add_header 'Access-Control-Allow-Headers' 'DNT,web-token,app-token,Authorization,Accept,Origin,Keep-Alive,User-Agent,X-Mx-ReqToken,X-Data-Type,X-Auth-Token,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range';
          add_header 'Access-Control-Expose-Headers' 'Content-Length,Content-Range';
			rewrite ^/api/(.*)$ /$1 break;
			#proxy_pass 你要跨域的的接口地址
			proxy_pass http://127.0.0.1:666/;
		}

    }
}

Native dns configuration

(If the above is not test-local.test.com, but directly your local localhost, you can directly change test-local.test.com to localhost or 127.0.0.1, otherwise configure dns resolution! )

Find the directory C:\Windows\System32\drivers\etc, open the hosts file, modify the file, add

127.0.0.1 a-local.test.com

Check configuration and reboot

Enter the installation directory and enter nginx -t to check whether there is any problem with the configuration

 Continue to enter nginx -s reloadrestart (after the nginx configuration file is modified, you must restart nginx to take effect)

refresh dns

ipconfig /flushdns

 Type in the browser http://a-local.test.comand you will see the code interface running locally

Successfully resolve cross-domain issues

Make a request:

	const baseUrl="http://a-local.test.com:8888";
    $.ajax({
			method:'get',
			url:baseUrl+'/getList',
			success:(res)=>{
				console.log("请求1得到的数据");
				console.log(res);
			}
		})

		$.ajax({
			method:'get',
			url:baseUrl+'/api/getList',
			success:(res)=>{
				console.log("请求2得到的数据");
				console.log(res);
			}
		})

The request is successful as shown in the figure

Additional:

nginx common commands

  • Help command: nginx -h

  • Start the Nginx server: start nginx

  • Configuration file path: /usr/local/nginx/conf/nginx.conf

  • Check the configuration file: nginx -t

  • Stop the service: nginx -s stop

  • Exit the service (stop the service after processing all requests): nginx -s quit

  • Reload the configuration file: nginx -s reload

  • show version info and exit nginx -v 

  • kill all nginx processes killall nginx 

Guess you like

Origin blog.csdn.net/enhenglhm/article/details/123791603