欢迎光临,了解微信小程序开发,就上易用通!

微信小程序访问豆瓣api403问题

发布:2018-05-09 15:39浏览: 来源:网络 作者:cola

通过豆瓣api可以获取很多电影、书籍等的数据信息。昨晚上用微信小程序请求豆瓣api,竟然被豆瓣拒绝了。(豆瓣设置了小程序的访问权限)。

问题

小程序请求是这样子:

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')
    },
  })
}


错误这样子

微信小程序访问豆瓣api403问题(图1)



解决

1、使用Nginx

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.94 Safari/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.94 Safari/537.36';

以此来代替小程序去请求豆瓣,然后把数据返回给小程序。

更改配置后保存,在nginx.exe 文件夹下打开命令窗口,输入start nginx,启动后每次修改配置,可以使用nginx -s reload




start nginx : 启动nginx

nginx -s reload :修改配置后重新加载生效

nginx -s reopen :重新打开日志文件

nginx -t -c /path/to/nginx.conf 测试nginx配置文件是否正确

关闭nginx:

nginx -s stop :快速停止nginx

nginx -s quit :完整有序的停止nginx

注意,我是在windows下进行开发和配置

如何使用:只需把请求的url的协议和域名替换成https://localhost/v2/,例如
https://api.douban.com/v2/book/1220562 =》https://localhost/v2/book/1220562



测试

onLoad: function (options) {
 this.getMoviesData('https://localhost/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')
    },
  })
}

 

竟然还是错误!!!

微信小程序访问豆瓣api403问题(图2)


状态码4xx客户端错误,400Bad Request 意思是我们发送了一个错误的请求。经过尝试发现,把header请求改成 header: { 'content-type': 'application/xml' }就可以了。额。。。明明获取的数据就是json,。。。可能是小程序后台对header做了限制。



终于等到你(正确测试)

onLoad: function (options) {
 this.getMoviesData('https://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')
    },
  })
}

微信小程序访问豆瓣api403问题(图3)

 





免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。