優惠公告:微享互動金秋十月、國慶感恩回饋活動于9.25-10.15正式開啟:網站建設、朋友圈廣告、小程序、抖音、短視頻、企業宣傳片等全系產品8.8折。 詳詢:023-62924115
微信可以通過調取API賦予小程序強大的功能,例如調取百度翻譯API可以用小程序翻譯,調取高德地圖API可以進行定位,而通過豆瓣api可以獲取很多電影、書籍等的數據信息。但微信小程序請求豆瓣api,會出現403問題導致被豆瓣拒絕。具體的問題和解決方案如下:
小程序請求代碼:
onLoad: function (options) {
this.getMoviesData(\'https://api.douban.com/v2/book/1220562\')
},
getMoviesData:function(url){
wx.request({
url: url,
data: {},
method: \'GET\',
header: {\'content-type\': \'application/json\' },
success: function (res){
console.log(res)
},
fail: function () {
console.log(\'fail\')
},
})
}
錯誤的類型
解決
1、使用Nginx
首先下載Nginx
解壓
打開解壓文件nginx-1.13.12(這是你的解壓文件名)/conf/nginx.conf
在文件中找到server {},在server {}下添加
location /v2/ {
proxy_store off;
proxy_redirect off;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Referer \'no-referrer-when-downgrade\';
proxy_set_header User-Agent \'Mozilla/5.0 (Windows NT 10.0;WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94Safari/537.36\';
proxy_connect_timeout 600;
proxy_read_timeout 600;
proxy_send_timeout 600;
proxy_pass https://api.douban.com/v2/;
}
重點是更改 proxy_set_header Referer \'no-referrer-when-downgrade\';
proxy_set_header User-Agent \'Mozilla/5.0 (Windows NT 10.0;WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94Safari/537.36\';
以此來代替小程序去請求豆瓣,然后把數據返回給小程序。
更改配置后保存,在nginx.exe 文件夾下打開命令窗口,輸入startnginx,啟動后每次修改配置,可以使用nginx -s reload
狀態碼4xx客戶端錯誤,400Bad Request 意思是我們發送了一個錯誤的請求。經過嘗試發現,把header請求改成 header: { \'content-type\': \'application/xml\' }就可以了。額。。。明明獲取的數據就是json,。。。可能是小程序后臺對header做了限制。
正確的代碼:
onLoad: function (options) {
this.getMoviesData(\'http://localhost/v2/book/1220562\')
},
getMoviesData:function(url){
wx.request({
url: url,
data: {},
method: \'GET\',
header: {\'content-type\': \'application/xml\' },
success: function (res){
console.log(res)
},
fail: function () {
console.log(\'fail\')
},
})
}
運行結果:
來源:重慶網站建設,本文網址:http://www.hq-gb.com/app-news/760.html,歡迎分享,(電話:15320293856,微信:llhhldancing)
馬上提交您的需求,我們會在24小時內聯系您,提供產品策劃服務!
網址:http://www.hq-gb.com
地址:重慶市兩江新區天王星C1棟3樓
座機:023-62924115
網站建設咨詢:18623514428 朱經理
朋友圈廣告咨詢:17783139095 文經理
微享官方微信
掃一掃 關注公眾號