Nginx初体验(本地模拟网络代理与反代理)

1,179 阅读2分钟

前端开发过程中我们经常会遇到跨域问题,那么应该怎么解决呢?

1.本地解决跨域

1.1 初始化vue项目

vue create vue-demo

具体细节可以 查看官网

1.2 创建node服务

const http = require('http');

http.createServer(function (request, response) {
    response.writeHead(200, {
        'Content-Type': 'application/json;charset=utf-8'
    });
    // 接口返回数据
    const data = {
        title: 'welcome nginx'
    };

    data = JSON.stringify(data);

    response.end(data);

}).listen(4396);
// 服务监听端口
console.log('server is listen at 4396 port');

1.3 查看并调用接口

  1. 浏览器查看 http://localhost:4396

  2. vue项目中调用

  • 下载 axios
npm install axios --save
  • 配置devServer

    在项目最外层目录新建一个 vue.config.js 文件

    module.exports = {
      publicPath: '/',
      outputDir: 'dist',
      assetsDir: 'static',
      devServer: {
        port: '8080',
        proxy: {
          '/api': {
            target: 'http://localhost:4396',
            ws: true,
            changeOrigin: true,
            pathRewrite: { '^/api': '/' }
          }
        }
      }
    }
    
  • 调用接口

    import axios from 'axios'
    
    created() {
      axios.get('http://localhost:4396').then(function(response){
        console.log(response);
      })
      axios.get('/api').then(function(response){
        console.log(response);
      })
    }
    

    调用后我们会发现没有使用代理的接口调用会出现跨域问题,但是通过api调用的则没有问题,好了现在我们已经解决了本地跨域问题,那么现在开始解决线上反代理问题

2. Nginx配置问题

2.1 下载 nginx nginx.org/en/download…

2.2 本地启动 nginx

  • 打开文件目录 双击 nginx.exe 或者 在当前目录下用命令行运行 nginx
  • 进入 conf 文件夹的 nginx.conf 进行编辑
http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen       5000;
        server_name  localhost;

        location / {
            root   html;
            index  index.html index.htm;
            try_files $uri $uri/ /index.html;
        }

        location /api {
          proxy_pass http://localhost:4396/;
        }

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

2.3 vue项目本地打包

npm run build

2.4 将打包文件 dist 目录下的文件都放入 html 目录下

2.5 启动nginx

2.6 打开 localhost:5000

2.7 修改 nginx 后需要重启

nginx -s reload

关闭端口

我们开启服务时经常会遇到端口被占用的情况, 此时可以查看本地端口被什么程序占用

在命令窗口中输入命令 netstat -aon|findstr "8080",引号的8080就是我们需要查询的端口号

netstat -aon|findstr "8080"

输入完成后,我们会看到界面上会弹出一个列表,列表第一行最后会出现一个数字,请记录下这个数字

例如:

image.png

此时 21412 和 18164

输入新的命令,查看端口被哪个程序占用着,tasklist|findstr "21412",命令引号中的数字就是前面列表第一行最后的数据

tasklist|findstr "21412"

image.png

此时我们可以看到是 nginx.exe 占用着

现在我们可以关闭 nginx.exe 来停用端口

taskkill /f /t /im nginx.exe

image.png

我们也可以通过任务管理器来关闭 nginx.exe

image.png

任务管理器中nginx 是有很多进程的, 我们可以通过任务号对应的关闭相应端口的 nginx 进程

over