通过Nginx配置解决跨域访问问题

问题背景

在前端访问资源会提示:*** has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. 这时就需要配置nginx代理来访问跨域资源。

Nginx配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
location /getjoke {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified- Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
proxy_pass https://v.juhe.cn/joke/content/list.php;
}

location /randJoke {
add_header 'Access-Control-Allow-Origin' "$http_origin" always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Allow-Methods' 'GET, OPTIONS' always;
add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified- Since,Keep-Alive,Origin,User-Agent,X-Requested-With' always;
proxy_pass https://v.juhe.cn/joke/randJoke.php?key=******;
}

配置后执行:

1
nginx -s reload

前端代码(vue)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
showJoke: function () {
var url="getjoke";
var timestamp=1539755239;
timestamp+=Math.floor(Math.random() * 10000000);
axios.get(url,{
params:{
key:'******',
page:1,
pagesize:1,
sort:'asc',
time:timestamp
}
}).then(resp => {
console.log(resp);
var joke=resp.data.result.data[0].content;
alert(joke);
}).catch(err => {
console.log('请求失败:'+err);
});
}