前端使用nginx 解决跨域问题
作为一个前端,必要时也是需要解决跨域问题的;
对于react 、vue 都有相关解决跨域问题的proxy;对于不使用框架的html页,解决跨域问题的方法之一就是使用nginx
下面是nginx的配置方法
server {
listen 8080; //配置端口
server_name localhost;
location / {
root html;
index index.html index.htm;//设置默认打开的文件
}
location /action/ { #匹配路径是以 /action开始的路径
proxy_read_timeout 180;
proxy_next_upstream http_502 http_504 error timeout invalid_header;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass http://www.baidu.com;//请求的第三方接口地址
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
接口的使用:
$.ajax({
type: "post",
url: "/action/getData",
data: {},
success: function (data) {
console.log("成功:", data);
},
error: function (error) {
console.log("发生错误:" , error);
}
});