正向代理
正向代理需要客户端特殊设置,才能访问到某个网站,例如google。
反向代理
反向代理是通过服务端设置,代理服务器用的,用户无感知。
开发vue项目时通过nginx反向代理访问文件地址和接口。
vue
服务端口 9527
/api/
请求地址(跨域)http://test.com:8882/
4399
nginx服务端口号(启动服务之后通过它来访问项目)
- 通过
http://localhost:4399
访问项目 - vue项目中请求地址若为
/getUserInfo
写为/api/getUserInfo
即可正常访问(解决跨域)
nginx.conf 配置
server {
listen 4399;
server_name localhost;
location / {
proxy_pass http://192.168.1.147:9527; #项目真实地址(写成http://localhost:9527访问很慢,不知道是啥原因)
}
location /api/ {
proxy_pass http://test.com:8882/; #跨域接口地址
}
}
开发时解决跨域更推荐这种方法
// vue.config.js
module.exports = {
devServer: {
proxy: {
'/api': {
target: 'http://test.com:8882',
changeOrigin: true,
pathRewrite: {
'^/api': '' // 这里理解成用‘/api’代替target里面的地址,比如调用'http://test.com:8882/users',直接写‘/api/users’即可
}
}
}
}
}