nginx: 利用反向代理解决跨域问题。
1. 服务端
服务端主要内容:
const http = require('http')
const PORT = 8222
const serverHandle = require('../app')
const server = http.createServer(serverHandle)
server.listen(PORT)
完整内容查看github: 服务端代码
启动: npm run dev
2. 客户端
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>博客首页</title>
<link rel="shortcut icon " type="images/x-icon" href="./favicon.ico">
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
</head>
<body>
<h1>首页</h1>
<script type="text/javascript">
function get (url) {
return $.get(url)
}
function post (url, data = {}) {
return $.ajax({
type: 'post',
url,
data: JSON.stringify(data),
contentType: "application/json",
})
}
let url = ''
get('http://localhost:3003/api/blog/list').then((res) => {
console.log("res----",res)
})
</script>
</body>
</html>
安装: npm install http-server -g
启动http服务: http-server -p 8333
3. nginx
下载nginx(mac): brew install nginx
命令(修改): sudo vi /usr/local/etc/nginx/nginx.conf
修改为如下:
http {
server {
listen 3003;
server_name localhost;
#charset koi8-r;
#access_log logs/host.access.log main;
#location / {
# root html;
# index index.html index.htm;
#}
location / {
proxy_pass http://localhost:8333;
}
location /api/ {
proxy_pass http://localhost:8222;
proxy_set_header Host $host;
}
}
}
说明:客户端:localhost: 8333 服务端: localhost: 8222;
- 当 server 监听3003 端口, 当访问localhost:3003 将转化为 localhost: 8333(客户端);
- 当访问包含http://localhost:3003/api/ 的链接的请求则会代理成http://localhost:8222(服务端);
- 浏览器访问http://localhost:3003 端口,这样即完成代理。解决跨域。