这篇文章主要是针对跨域进行配置,若是大佬们会配置的话,就不用看了~html
举个反向代理例子,我(客户端)让朋友(代理)去给我买瓶水,并无说去哪里买,反正朋友(代理)买回来了,对于我(客户端)来说,我(客户端)感知不到超市(服务器)的存在,这就是反向代理。node
简单归纳下就是,服务器代理被称为反向代理,客户端代理被称为正向代理。
nginx
http://nginx.org/en/download.htmljson
在这个目录下,打开cmd命令行,输入nginx,你也能够双击nginx.exe,但显得不直观,访问Localhost:80端口,就能够看到下方的界面,
api
不想要的话,能够自行修改,进入配置文件目录,跨域
删除注释和无关代码后的文件长这样:bash
先来启动一个node服务:服务器
const http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'application/json;charset=utf-8'
});
// 这个例子中要回传的data
let data = {
name: 'nginx proxy'
};
data = JSON.stringify(data);
response.end(data);
}).listen(8887);
console.log('server1 is listen at 8887 port');复制代码
启动服务后,咱们直接进行访问,模拟跨域场景:app
<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)
}
}
}
</script>
</body>复制代码
果不其然报了跨域的错误:优化
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
}
}
}
复制代码
咱们在location里面加上两个字段:
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
server {
listen 80;
server_name localhost;
location / {
proxy_pass http://localhost:8887;
add_header Access-Control-Allow-Origin *;
}
}
}复制代码
如今修改下请求的代码:
<body>
<h1>nginx反向代理</h1>
<script>
var xhr = new XMLHttpRequest();
// 在这里把原来的localhost:8887修改为localhost:80
xhr.open('GET', 'http://localhost:80');
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
console.log(xhr)
}
}
}
</script>
</body>复制代码
修改完毕后重启服务,这里提供两种方式,不过都得在文件目录下新开一个cmd命令行,
nginx -s reload复制代码
nginx -s stop
nginx复制代码
若是是想对服务器上的api文件夹下发请求的话,那就只须要修改配置文件中的这个字段就行,
location /api {
// 你的代码,如
// proxy_pass 你的路径
// add_header Access-Control-Allow-Origin *;}复制代码