豆瓣好像禁了小程序的接口调用,返回403错误。网上查了一圈豆瓣应该是通过headers里的referer判断的。
可是wx.request(OBJECT)又不能更改referer。
网上都是用nginx来搞的,无奈我这菜B还不会用。。。
所以就自己试着用node做服务器代理。
上代码:
var express = require("express");
var app = express();
var proxy = require("http-proxy-middleware");
var cors = require("cors");
var apiproxy = [proxy("/v2/movie/top250", {
target: "https://api.douban.com",
changeOrigin: true
}), proxy("/*", {
target: "http://localhost:3000",
changeOrigin: true
})];
app.use(cors());
app.use((req, res, next) => {
req.headers = {
"accept": "*/*",
"accept-encoding": "gzip, deflate, sdch, br",
"accept-language": "zh-CN,zh;q=0.8",
"cache-control": "no-cache",
"connection": "keep-alive",
"host": "localhost:5000",
"origin": "http://localhost:8080",
"pragma": "no-cache",
"referer": "http://localhost:8080/",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36"
}
next();
});
app.use((req, res, next) => {
console.log(req.headers.referer);
next();
})
app.use(apiproxy);
app.listen(5000, () => {
console.log("port on 5000")
});
写了个中间件,headers的设置直接用了普通浏览器里请求api的设置。
wx.request({
url: "http://localhost:5000/v2/movie/top250",
success(res) {
console.log(res.data);
}
})
搞定!