前言
做了一個簡單頁面嗡午,做了一些數(shù)據(jù)埋點汰扭,想通過企業(yè)微信機器人來推送數(shù)據(jù)稠肘,遇到了一些問題,順便記錄下萝毛。
跨域問題的解決思路
由于是項目比較簡單项阴,直接使用了ajax去請求,代碼如下
$.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);
??}
})
請求的時候發(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.
這里為什么會跨域呢笆包?因為我在我自己域名上去請求其他域名环揽。
一般跨域的解決方案
??jsonp(維信機器人接口只支持json)
??后端設(shè)置跨域 (改不了微信接口的后臺)
那有什么方案呢?
思路決定出路庵佣。
先明白問題所在歉胶,是因為瀏覽器同源政策導(dǎo)致跨域的問題,那我請求的域名是同源的不就好了嗎巴粪?
下面說下具體方法
??使用nginx進行轉(zhuǎn)發(fā)
我只需要把ajax請求的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ā)來實現(xiàn)
nginx轉(zhuǎn)發(fā)請求從POST變成GET
可以看到上面的配置是post請求到nginx辫塌,nginx在把請求轉(zhuǎn)發(fā)到企業(yè)微信接口
第一次http請求是post,第二次居然自動轉(zhuǎn)換成get派哲。
原來nginx在配置location的時候臼氨,如果多了/,那么會自動變成get
修改后如下
?location?/test?{
????????proxy_pass?https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b38aa4d8-a08e-4a91;
????????proxy_method?POST;}