這篇文章主要是針對跨域進行配置,若是大佬們會配置的話,就不用看了~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 *;}複製代碼