使用 nginx 代理
nginx 的代理配置是在 http 块下的 server 进行配置 server 首级下的 listen 是 nginx 的端口号 server_name 是 nginx 的 ip 代理配置使用 location 配置
案例
- 使用 nginx 代理到百度
当我们在浏览器访问
http:localhost:9999/test时候会跳转到百度首页
server {
listen 9999;
server_name localhost;
location /test {
root html;
index index.html index.htm;
proxy_pass https://www.baidu.com/;
}
}
- 使用 nginx 代理解决跨域
前端代码
const btn = document.querySelector('button');
btn.onclick = () => {
fetch('http://localhost:9999/proxy/test')
.then((res) => res.json())
.then((res) => {
console.log(res, '===>>');
});
};
后端代码 这里使用 express 快速启动一个服务
import express from 'express';
const app = express();
app.get('/proxy/test', (req, res) => {
res.json({
code: 200,
message: 'success',
data: {
name: 'tom',
age: 18,
},
});
});
app.listen(3000, () => {
console.log('server running at http://localhost:3000');
});
nginx 配置
server {
listen 9999;
server_name localhost;
location /proxy {
proxy_pass http://localhost:3000;
add_header 'Access-Control-Allow-Origin' '*'
}
}
其中 nginx 配置 add_header 'Access-Control-Allow-Origin' '*' 是允许所有请求跨域访问