mac下安装nginx并且利用nginx解决本地前端工程访问后端接口跨域问题

安装nginx

环境:macos

mac环境下是使用的brew安装nginx

1.终端输入 brew search nginx 查找nginx

2.安装指令 brew install nginx

安装完成后会在终端中看到一些nginx的安装信息

3.配置nginx

3.1 终端下进入目录 cd /usr/local/

3.2 打开nginx配置文件所在目录 open nginx/

配置文件为 nginx.conf

3.4 启动nginx 指令为:

brew services start nginx

 

重启指令:

brew services restart nginx

 

到此nginx安装完毕

 

下面介绍利用nginx解决前端页面访问后端接口跨域问题

 

 

跨域问题配置

 

1.进入目录 /usr/local/nginx ,修改配置文件nginx.conf,关键配置内容如下

listen 80; #原为8080,避免冲突,更改为80
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;


        location / {
            proxy_pass   http://127.0.0.1:8848;        # 前端静态页面地址,本人使用的HBuilderX编辑器,其工程默认端口为8848,可根据自己的项目情况修改
            proxy_redirect default;
            #设置主机头和客户端真实地址,以便服务器获取客户端真实IP
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;                
        }

        location /apis {                            # 自定义nginx接口前缀
            rewrite  ^/apis/(.*)$ /$1 break;        # 监听所有/apis前缀,是则转发后台api接口地址
            include  uwsgi_params;
            proxy_pass   http://127.0.0.1:9099;        # 后台api接口地址
            #设置主机头和客户端真实地址,以便服务器获取客户端真实IP
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;                
        }

保存配置后,终端输入指令 brew services restart nginx 重启nginx

相应的前端ajax调用接口地址改为如下

$.ajax({
    type:"POST",
    url:"/apis/xxx/xxx",//根据监听的apis前缀,指向后端接口
    data:{'xxx':'xxx'},
    success:function (data) {
        
    }

最后浏览器地址栏输入自己的前端工程地址 http://127.0.0.1:80/projectname/xxx.html

猜你喜欢

转载自www.cnblogs.com/vicF/p/9822526.html