微信小程序网络之上传下载(代码篇)(5)

  • • 发表于 4年前
  • • 作者 Fredia
  • • 4190 人浏览
  • • 8 条评论
  • • 最后编辑时间 4年前
  • • 来自 [技 术]

原创声明:本文为作者原创,未经允许不得转载,经授权转载需注明作者和出处

STEP 06 微信小程序代码问题分析

源码地址:https://github.com/CFETeam/weapp-demo-album
通讯所需要修改的host
这儿修改成自己的host,全局常量嘛
官方demo 是开发工具0.9版本出的,那时候有Promise 方法,现已移除
直接运行会报如下错误:

promise错误

Promise is not a constructor

解决方案:
在request.js文件头加上一个引用:

var Promise=require('./bluebird.min.js');
module.exports = (options) => {
    return new Promise((resolve, reject) => {
        options = Object.assign(options, {
            success(result) {
                if (result.statusCode === 200) {
                    resolve(result.data);
                } else {
                    reject(result);
                }
            },

            fail: reject,
        });

        console.log(options);
        wx.request(options);
    });
};

“bluebird.min.js”文件可以到百度官方下载(77.4kb)
这里涉及的ES5与ES6 可以参考其他文章学习
api.js中:

var config = require('../config.js');

module.exports = {
    getUrl(route) {
        return `https://${config.host}${config.basePath}${route}`;
    },
};

即可看到访问的api方法

STEP 07 微信相册程序JS分析调试

/page/album/album.js就是我们的核心啦

onload方法
onLoad() {
        this.renderAlbumList();  这一步进行渲染相册列表

        this.getAlbumList().then((resp) => {  request 访问我们服务器再加载数据到页面的"albumlist" list集合
            console.log(resp.data);

            this.setData({ 'albumList': this.data.albumList.concat(resp.data) });
            this.renderAlbumList(); 再次渲染
        });
    },
getAlbumList方法
// 获取相册列表
    getAlbumList() {
        this.showLoading('加载列表中…');
        setTimeout(() => this.hideLoading(), 1000);
        return request({ method: 'GET', url: api.getUrl('/list') });  
    },

打印出来的访问:

{method: “GET”, url: “https://www.wxapptest.cc/applet/album/list"}

renderAlbumList方法(这个不是重点)
// 渲染相册列表
    renderAlbumList() {
        let layoutColumnSize = this.data.layoutColumnSize;
        let layoutList = [];
        console.log(this.data.albumList.length);
        if (this.data.albumList.length) {
            console.log("失败2");
            layoutList = listToMatrix([0].concat(this.data.albumList), layoutColumnSize);
            console.log(layoutList);
            let lastRow = layoutList[layoutList.length - 1];
            if (lastRow.length < layoutColumnSize) {
                let supplement = Array(layoutColumnSize - lastRow.length).fill(0);
                lastRow.push(...supplement);
            }
        }
        console.log("失败3");
        this.setData({ layoutList });
    },
chooseImage方法(前面这么多废话,就只是为了它 !上传)
 // 从相册选择照片或拍摄照片
chooseImage() {
        wx.chooseImage({
            count: 9,
            sizeType: ['original', 'compressed'],
            sourceType: ['album', 'camera'],

            success: (res) => {
                this.showLoading('正在上传图片…');

                console.log(api.getUrl('/upload'));
                wx.uploadFile({
                    url: api.getUrl('/upload'),
                    filePath: res.tempFilePaths[0],
                    name: 'image',

                    success: (res) => {
                        let response = JSON.parse(res.data);

                        if (response.code === 0) {
                            console.log(response);

                            let albumList = this.data.albumList;
                            albumList.unshift(response.data.imgUrl);

                            this.setData({ albumList });
                            this.renderAlbumList();

                            this.showToast('图片上传成功');
                        } else {
                            console.log(response);
                        }
                    },

                    fail: (res) => {
                        console.log('fail', res);
                    },

                    complete: () => {
                        this.hideLoading();
                    },
                });

            },
        });
    },

分析重点

       wx.uploadFile({
                    url: api.getUrl('/upload'),    访问的是这个: https://www.wxapptest.cc/applet/album/upload
                    filePath: res.tempFilePaths[0],
                    name: 'image',

                    success: (res) => {
                        let response = JSON.parse(res.data);

                        if (response.code === 0) {
                            console.log(response);

                            let albumList = this.data.albumList;
                            albumList.unshift(response.data.imgUrl);   获取上传后的img的url

                            this.setData({ albumList });
                            this.renderAlbumList();  重新刷新渲染页面

                            this.showToast('图片上传成功');
                        } else {
                            console.log(response);
                        }
                    },

                    fail: (res) => {
                        console.log('fail', res);
                    },

                    complete: () => {
                        this.hideLoading();
                    },
                });

大致效果如下:

504.gif

服务端问题,前文提过

出现这个问题莫慌。分析问题出在哪儿,是APP端问题还是SERVER响应问题
先从APP端debug开始:

1.分析APP请求

请求是发送成功的了
只是服务器返回的执行的是fail 方法,说明APP没问题

详细
uploadfile方法其实很简单,但是我们要学会分析问题的方法
我们继续追踪到这个请求,看服务器有没有接收到

从APP到nginx到nodejs再到对象服务器(COS)

2.接着我们开始查nginx 的log日志

nginx日志在/etc/nginx/logs文件夹下
cd /etc/nginx/logs tail www.qcloud.la.error.log //查看
查看日志

贴上日志:

2016/12/05 01:16:15 [error] 3731#3731: *10 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 101.244.40.73, server: www.wxapptest.cc, request: "POST /applet/album/upload HTTP/1.1", upstream: "http://127.0.0.1:9993/applet/album/upload", host: "www.wxapptest.cc"
2016/12/05 01:17:10 [error] 3731#3731: *14 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 101.244.40.73, server: www.wxapptest.cc, request: "POST /applet/alb
![Uploading 77554422121jdf2322w_667991.gif . . .]um/upload HTTP/1.1", upstream: "http://127.0.0.1:9993/applet/album/upload", host: "www.wxapptest.cc"
2016/12/05 01:23:29 [error] 3731#3731: *16 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 101.244.40.73, server: www.wxapptest.cc, request: "POST /applet/album/upload HTTP/1.1", upstream: "http://127.0.0.1:9993/applet/album/upload", host: "www.wxapptest.cc"
2016/12/05 01:23:53 [error] 3731#3731: *20 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 101.244.40.73, server: www.wxapptest.cc, request: "POST /applet/album/upload HTTP/1.1", upstream: "http://127.0.0.1:9993/applet/album/upload", host: "www.wxapptest.cc"
2016/12/05 01:25:00 [error] 3731#3731: *23 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 101.244.40.73, server: www.wxapptest.cc, request: "POST /applet/album/upload HTTP/1.1", upstream: "http://127.0.0.1:9993/applet/album/upload", host: "www.wxapptest.cc"
2016/12/05 01:26:54 [error] 3731#3731: *28 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 101.244.40.73, server: www.wxapptest.cc, request: "POST /applet/album/upload HTTP/1.1", upstream: "http://127.0.0.1:9993/applet/album/upload", host: "www.wxapptest.cc"

发现nginx服务器能接受此stream请求,说明nginx并没有问题

3.接着我们开始查nodejs的log日志

前文中说过

pm2 show 0  指令标明了nodejs进程运行的日志路径

打开到根路径:

cd /root/.pm2/logs
tail album-out.log

操作如下:

接收到请求

# tail album-out.log 
POST /applet/album/upload - - - - ms
GET /applet/album/list 200 36 - 18.726 ms
GET /applet/album/list 200 36 - 17.683 ms
POST /applet/album/upload - - - - ms
POST /applet/album/upload - - - - ms
POST /applet/album/upload - - - - ms
GET /applet/album/list 200 36 - 16.605 ms
GET /applet/album/list 200 36 - 19.785 ms
GET /applet/album/list 200 36 - 19.398 ms
POST /applet/album/upload - - - - ms

日志已经接收到了POST方法,没毛病
所以,对于此项目我折腾很久也没运行起来(主要我并不会nodejs而且COS新版SDK没时间去看)
总结出是nodejs项目与COS直接的读取存储接口发生了问题

downloadImage方法
 // 下载图片
    downloadImage() {
        this.showLoading('正在保存图片…');
        console.log('download_image_url', this.data.imageInAction);

        wx.downloadFile({
            url: this.data.imageInAction,
            type: 'image',
            success: (resp) => {
                wx.saveFile({
                    tempFilePath: resp.tempFilePath,
                    success: (resp) => {
                        this.showToast('图片保存成功');
                    },

                    fail: (resp) => {
                        console.log('fail', resp);
                    },

                    complete: (resp) => {
                        console.log('complete', resp);
                        this.hideLoading();
                    },
                });
            },

            fail: (resp) => {
                console.log('fail', resp);
            },
        });

        this.setData({ showActionsSheet: false, imageInAction: '' });
    },

其实前面讲了那么多了,这个wx.downloadFile()方法显得特别容易理解了
那些重复的话我就不写了

针对了腾讯相册这个demo写了4篇进行了梳理,虽然最后没跑通,或许是实力欠缺,但是腾讯也太坑了。四篇文章梳理一个完整的全程小程序搭建已经网络通讯的分析调试

此系列若有讲错的地方,请各位给点建议,互相学习共同提高!!!

分享到:
评论区(共8条评论)
8条评论
Ctrl+Enter
作者

Fredia

Fredia

APP:1 帖子:12 回复:30 积分:552

已加入社区[1415]天

CTOWAY

作者详情》
Top