nginx实现跨域详细教程,附带前后端实例

去官网下载nginx

为了方便启动和关闭nginx,按照如图新建start.bat,stop.bat文件,双击即可在windows下启动、关闭nginx
在这里插入图片描述
start.bat代码:


start nginx

echo success

pause

stop.bat代码

nginx.exe -s stop

echo success

pause

当然为了方便,也可以新建一个isRun.bat;来检查是否启动成功
isRun.bat代码

tasklist /fi "imagename eq nginx.exe"
echo "isRun?"
pause

在这里插入图片描述
看到上图就是启动成功,没有就是失败,看logs/error.log,查看错误信息,百度一下。
注意文件夹不能有中文。

配置目录:nginx-1.14.1\conf\nginx.conf
主要配置:

 server {
#  nginx监听的端口     
        listen       1999;
# 前端项目ip,可以localhost
        server_name  172.30.34.180;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;
# 前端项目的端口
        location / {
         	proxy_pass  http://172.30.34.180:8080/;
        }
# 服务端的ip端口        
        location /myServer {
         	proxy_pass  http://172.30.34.180:3000/;
        }

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }

测试代码前端代码:

/* eslint-disable */
<template>
  <div>
    <button @click="test">测试</button>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  methods: {
    test () {
      axios.get('/myServer').then(res => {
        console.log(res)
      })
    }
  }
}
</script>

测试后端nodejs代码片段:

var fn_index = async (ctx, next) => {

  console.log(html)
  ctx.response.body = {
    state: 200,
    data: {
      list: [{ userName: "张三", id: 3 }, { userName: "李四", id: 4 }]
    }
  };
  console.log(ctx.response)
};

服务端端口3000
效果图:
注意:一定要用nginx listen的端口
在这里插入图片描述

成功跨域!
提示:上线时需要把nginx一并上线,根据具体的服务器配置

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值