前端跨域問題的解決思路
前言
做了一個(gè)簡(jiǎn)單頁面,做了一些數(shù)據(jù)埋點(diǎn),想通過企業(yè)微信機(jī)器人來推送數(shù)據(jù),遇到了一些問題,順便記錄下。
跨域問題的解決思路
由于是項(xiàng)目比較簡(jiǎn)單,直接使用了ajax去請(qǐng)求,代碼如下
$.ajax({
??type:?'POST',
??url:?'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91-',
??async:?true,
??data:?$.toJSON(data),
??contentType:'application/json;charset=utf-8',
??dataType:?'json',
??success:?function?(data)?{
????console.log("data",data)
??},
??error:?function?(error)?{
????console.log("error",error);
??}
})
請(qǐng)求的時(shí)候發(fā)現(xiàn)了跨域問題
Access?to?XMLHttpRequest?at?'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91-'?from?origin?'null'?has?been?blocked?by?CORS?policy:?Response?to?preflight?request?doesn't?pass?access?control?check:?No?'Access-Control-Allow-Origin'?header?is?present?on?the?requested?resource.
這里為什么會(huì)跨域呢?因?yàn)槲以谖易约河蛎先フ?qǐng)求其他域名。
一般跨域的解決方案
??jsonp(維信機(jī)器人接口只支持json)
??后端設(shè)置跨域 (改不了微信接口的后臺(tái))
那有什么方案呢?
思路決定出路。
先明白問題所在,是因?yàn)闉g覽器同源政策導(dǎo)致跨域的問題,那我請(qǐng)求的域名是同源的不就好了嗎?
下面說下具體方法
??使用nginx進(jìn)行轉(zhuǎn)發(fā)
我只需要把a(bǔ)jax請(qǐng)求的url更換成自己的域名,然后使用nginx轉(zhuǎn)發(fā)到企業(yè)微信接口,就完美繞開了跨域問題
$.ajax({
??type:?'POST',
??url:?'https://domain/test',
??async:?true,
??data:?$.toJSON(data),
??contentType:'application/json;charset=utf-8',
??dataType:?'json',
??success:?function?(data)?{
????console.log("data",data)
??},
??error:?function?(error)?{
????console.log("error",error);
??}
})
??nginx配置
?location?/test/?{
????????proxy_pass?https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91;
????????proxy_method?POST;
}
??這樣就解決了跨域的問題,通過服務(wù)器轉(zhuǎn)發(fā)來實(shí)現(xiàn)
nginx轉(zhuǎn)發(fā)請(qǐng)求從POST變成GET
可以看到上面的配置是post請(qǐng)求到nginx,nginx在把請(qǐng)求轉(zhuǎn)發(fā)到企業(yè)微信接口
第一次http請(qǐng)求是post,第二次居然自動(dòng)轉(zhuǎn)換成get。
原來nginx在配置location的時(shí)候,如果多了/,那么會(huì)自動(dòng)變成get
修改后如下
?location?/test?{
????????proxy_pass?https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91;
????????proxy_method?POST;
}