Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

nginx处理跨域 #44

Open
reng99 opened this issue Aug 8, 2019 · 0 comments
Open

nginx处理跨域 #44

reng99 opened this issue Aug 8, 2019 · 0 comments
Labels
javascript javascript tag nginx

Comments

@reng99
Copy link
Owner

reng99 commented Aug 8, 2019

为什么要抛出这个话题?

最近从mac转成用window来开发,在安装nginx的时候碰了下钉子,那我就不开心了。想着既然都安装好了,那么就搞点事情吧~

window上安装nginx

简单讲下在window上安装nginx~

下载软件并安装

基本操作

进入解压的文件夹(nginx.exe)的上一级。

  • 启动:nginx
    • 启动之后就可以在localhost:80访问你的项目了,前提是你的80端口没有被占用
  • 停止
    • 快速停止:nginx -s stop
    • 优雅停止:nginx -s quit
  • 重新加载:nginx -s reload
    • 使用情况-更改配置;开启一个新的工作进程;优雅关闭了旧的工作进程想重新启动
  • 重新打开:nginx -s reopen
    • 重新打开日志文件

注意事项

在出现pid被占用的情况,你可以通过下面的方法处理:

  1. 在任务管理器中手动移除nginx占用的进程

  2. 执行tasklist /fi "imagename eq nginx.exe"找出nginx占用的进程

映像名称                       PID 会话名              会话#       内存使用
========================= ======== ================ =========== ============
nginx.exe                     8248 Console                    1      7,076 K
nginx.exe                     3052 Console                    1      7,508 K

之后kill相关的进程就行了。

注意:有时候移除了占用的PID后还是不行,那重启下电脑~

启动nginx后,在浏览器上输入localhost你会看到其成功启动的页面,如下图:

nginx-start

跨域问题

对于跨域的概念就不详细说了...

我们先关闭nginx代理,然后开启两个node服务来进行验证,刚开始的时候,我是这样处理的:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>nginx</title>
</head>
<body>
    <h1>nginx反向代理</h1>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost:8887');
        xhr.send();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    console.log(xhr.responseText)
                }
            }
        }
    </script>
</body>
</html>

我开启了第一个服务server.js

const http = require('http');
const fs = require('fs');

http.createServer(function(request, response) {
    const html = fs.readFileSync('index.html', 'utf8');
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });
    response.end(html);
}).listen(8888);

console.log('server is listening at 8888 port');

好,我开启第二个服务来提供数据源server2.js

const http = require('http');

http.createServer(function(request, response) {
    response.writeHead(200, {
        'Content-Type' : 'application/json;charset=utf-8'
    });

    let data = {
        name: 'nginx proxy'
    };

    data = JSON.stringify(data);

    response.end(data);

}).listen(8887);

console.log('server2 is listen at 8887 port');

可是由于浏览器的同源策略,我没能请求到数据~

port8888

我的另外一个开启的服务是有数据的:

port8887

来,nginx派上用场了,我修改下上面html个文件的代码,如下:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>nginx</title>
</head>
<body>
    <h1>nginx反向代理</h1>
    <script>
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'http://localhost/api');
        xhr.send();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    console.log(xhr.responseText)
                }
            }
        }
    </script>
</body>
</html>

nginx代理

来,我们修改下nginx.conf文件,如下:

http {
    server {
        ...
        location / {
            root   html;
            index  index.html index.htm;
        }
        # 加入的内容
        location /app/ {
            proxy_pass http://localhost:8888/;
        }
        # 加入的内容
        location /api/ {
            proxy_pass http://localhost:8887/;
        }
    }
}

然后开启我们的nginx服务之后,就重启server.jsserver2.js服务。之后在浏览器上打开localhost/app/就在console上看到请求过来的数据了~

success-data

参考和后话

更多的内容,请戳我的博客进行了解,能留个star就更好了💨

@reng99 reng99 added javascript javascript tag nginx labels Aug 8, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
javascript javascript tag nginx
Projects
None yet
Development

No branches or pull requests

1 participant