前端使用nginx解决跨域问题

355 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第16天,点击查看活动详情

前言

在项目中,可能后端的接口各种跨域,我们今天来介绍一下,使用nginx做反向代理来解决跨域问题

nginx的实际使用

官网下载nginx稳定版,接下来以windows系统为例

nginx的下载页面

image.png

下载拿到nginx文件夹如图所示

image.png

在这里我们主要关心confhtml文件夹

  • conf: 里边主要包括nginx的各种配置
  • html: 是nginx默认的系统访问根目录

conf中的nginx.conf 是我们nginx.conf的配置文件,打开看一下

    
#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 {
        listen       9932;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   html;
            index  index.html index.htm;
        }
        location /uploadFile/ {
            proxy_pass http://192.168.100.40:9955;
        }
        location /api/ {
            proxy_pass http://192.168.100.40:9955;
        }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }


    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

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


    # HTTPS server
    #
    #server {
    #    listen       443 ssl;
    #    server_name  localhost;

    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_cache    shared:SSL:1m;
    #    ssl_session_timeout  5m;

    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers  on;

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

    }    

其中server下的

  • listen 代表你nginx启动后的端口号

  • server_name 代表你nginx启动后的ip

如图是所示,按此配置打开后的nginx服务,就是本地的9932端口

再往下看

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

location是nginx中的块级指令(block directive),,location指令的功能是用来匹配不同的url请求,进而对请求做不同的处理和响应

这一部分的代码代表默认的网站根目录是html文件夹,也就是上文中说到的html文件夹

默认的html页面是index.html

location /uploadFile/ {

            proxy_pass http://192.168.100.40:9955 **;**

 }

这一段代表,我们浏览器遇到了/uploadFile就 自动代理到http://192.168.100.40:9955这个地址,这样完美解决了跨域问题

举个例子

根据浏览器的跨域规则

端口号和ip只要有一个不同就跨域

我们原本的接口地址是http://192.168.100.40:9955/uploadFile 是这个

我们发起请求的地址的端口号是9932

这样肯定跨域

那么如果我们把uploadFile代理到了http://192.168.100.40:9955呢,就代表只要我们请求localhost:9932/uploadFile,其实就是做了个反向代理,nginx帮我们请求http://192.168.100.40:9955/uploadFile

同理我们项目中要将请求的原本ip和端口号换掉,只保留/uploadFile

const instance = axios.create({
  baseURL: "/uploadFile",
  timeout: 60000,
  crossDomain: true,
  responseType: "json"
});

启动nginx

放置我们的项目代码

修改完上述配置后,我们回到最开始的目录,打开html文件夹,将里边最初的内容全部删除,换成我们的项目包的内容,如图所示。此处也有index.html, 正好对应配置里的index.html

image.png

启动nginx

在nginx的主目录打开终端,在终端中输入命令

nginx的常用命令如下

  • 启动: start nginx 也可以双击目录中的nginx.exe 启动,就那个绿色图标

  • 重新启动:nginx -s reload  (一般在修改配置文件后使用)

  • 快速停止nginx,可能并不保存相关信息:nginx -s stop

  • 关闭nginx,完整有序的停止nginx,保存相关信息: nginx -s quit

注:nginx所放置的路径中不能存在中文字符,否则启动会失败

做完上述操作后,打开浏览器输入配置的端口号和ip地址进行验证