1.本节主要解决Ubuntu,nginx中 html项目发布后访问c#接口跨域的问题。
2.现在架构是:html 发布在nginx中,c#接口发布在iis , 现在需要让nginx 反向代理已经发布好的iis接口后台. html中可以Axios调用接口.
3.nginx.conf配置
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;
events {
worker_connections 768;
# multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
gzip on;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
#第一个网站
server {
listen 81;
server_name localhost;
location / {
root /etc/nginx/html/web1/;
index index.html index.htm;
}
}
#第二个网站
server {
listen 82;
server_name localhost;
location / {#静态前台网站
root /etc/nginx/html/vue1/vue_test/dist/;
index index.html index.htm;
}
location /api/ {#这里处理跨域
#后台C#接口代理 这个库
proxy_pass http://172.16.6.133:83/; #将backend-server替换为后端服务器的地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
}
#反向代理后台
server {
listen 83;
server_name 192.168.21.128; #将yourdomain.com替换为你自己的域名或IP地址
location /api/ {
proxy_pass http://172.16.6.133:83/; #将backend-server替换为后端服务器的地址
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Headers X-Requested-With;
add_header Access-Control-Allow-Methods GET,POST,OPTIONS;
}
}
}
vue 组件中 axios 调用
Getaxiosfun: function () {
//使用get
//开发 http://localhost:8080/api/Home/GetStudents?name=123
//iis http://172.16.6.133:8051/api/Home/GetStudents?name=123
//nginx http://192.168.21.128:82/api/Home/GetStudents?name=123
axios.get('http://192.168.21.128:82/api/Home/GetStudents?name=123').then(
(response) => {
alert((this.Message = response.data));
}, //成功回调
(error) => {
alert((this.Message = error.message));
} //失败回调
);
},
Postaxiosfun: function () {
//使用post
axios.post('http://192.168.21.128:82/api/Home/GetStudents2', {name: '0123456',})
.then(
(response) => {
alert((this.Message = response.data));
}, //成功回调
(error) => {
alert((this.Message = error.message));
} //失败回调
);
},
题外话:ubuntu 中修改nginx的 nginx.conf 配置 可以在桌面修改好 在复制进去 ,获取用命令 复制进去etc/nginx中。
nginx 其实就是配置实现代理或web服务器。