正向代理和反向代理
提到代理,肯定要说一下这两个的区别。
举个正向代理的例子:我打球累了走不动了,找看球的小朋友帮我去旁边的商店买瓶水。商店老板是不知道到底是谁需要喝水的,隐藏了客户端。当然,小朋友可以告诉老板就是那个打球像蔡徐坤的人要喝水。还有,VPN 就是正向代理。
反向代理的例子:我打球累了,找看球的小朋友要瓶水喝(当然我肯定会给钱的:D)。我不需要知道小朋友的水是从旁边的商店还是两公里外的超市买的。隐藏了服务端。还有,我们连好了 VPN 访问谷歌的时候,浏览的那些页面,我们是不会知道具体是哪台服务器的资源。
具体步骤
- 测试页面
然后,我们写一个简单的 ajax 请求页面。你可以本地用http-server
启动(见下面启动方法)访问下,可以发现请求跨域了:
<html>
<head>
<title></title>
</head>
<body>
<button onclick="sendAjax()">sendAjax</button>
<script type="text/javascript">
var sendAjax = () => {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:8080/login',{ account: 'admin', password: 'admin' });
xhr.send();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
}
</script>
</body>
</html>
复制代码
==========================================================================================================================
- 安装 Nginx
这个时候,你可以通过设置响应头来允许跨域。或者用 Nginx 来解决这个问题了。首先肯定需要安装 Nginx。这个按照对应的平台安装就行了。
brew update
brew install nginx
nginx
nginx -s reload // 重启
复制代码
- 配置
然后我们配置一下代理,这个意思就是我们请求中有 /api 这样的就会代理到 http://127.0.0.1:8080,所以我们只要访问 /api/login 这个不跨域的接口,然后就会由服务器反向代理到 http://10.16.254.95[/login。](https://link.zhihu.com/?target=http%3A//localhost%3A666/api/getList%25E3%2580%2582)
listen 9999;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
location / {
root html;
index index.html index.htm;
}
location /api/ {
proxy_pass http://10.16.254.95:9527;
}
复制代码
配置好之后我们需要重启一下 Nginx 服务。注意一点,重启时可能会报这么一个错误:
nginx: [error] open() "/usr/local/var/run/nginx.pid" failed (2: No such file or directory)
复制代码
这是 sudo nginx -s stop
这个命令会删除 pid 文件,可以执行 sudo nginx
重新添加这个文件。
- 测试结果
这个时候,我们不用绝对地址了,我们把ajax请求里面的接口换成相对地址:
// xhr.open('GET', 'http://localhost:8080/login');
xhr.open('GET', '/api/login');
复制代码
控制台就不会报跨域啦
使用http-server开启一个本地服务器
前言
在写前端页面中,经常会在浏览器运行HTML页面,从本地文件夹中直接打开的一般都是file
协议,当代码中存在http
或https
的链接时,HTML页面就无法正常打开,为了解决这种情况,需要在在本地开启一个本地的服务器。
本文是利用node.js
中的http-server
,开启本地服务,步骤如下:
1 下载node.js
官网地址: nodejs.org
下载完成后在命令行输入命令$ node -v
以及$ npm -v
检查版本,确认是否安装成功。
2 下载http-server
在终端输入:
$ npm install http-server -g
3 开启 http-server服务
终端进入目标文件夹,然后在终端输入:
$ http-server -c-1 (⚠️只输入http-server的话,更新了代码后,页面不会同步更新)
Starting up http-server, serving ./
Available on:
http://127.0.0.1:8080
http://192.168.8.196:8080
Hit CTRL-C to stop the server
复制代码
4 关闭 http-server服务
按快捷键CTRL-C
终端显示^Chttp-server stopped.
即关闭服务成功。