NodeJS用request上传图片到微信公众平台接口

微信公众平台的这个素材上传接口比较奇怪,用axios始终无法成功,而使用request库,可用如下方法上传成功

import request from 'request';

const uploadImage = async (fileUrl) => {
    const url = `https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=${YOUR_ACCESS_TOKEN}`;
    const formData = {
        media: (await axios.get(fileUrl, { responseType: 'stream' })).data,
    }
    try {
        const res = await new Promise(async (resolve, reject) => {
            request({
                url,
                method: 'post',
                formData,
                json: true,
            }, (err, response) => {
                if (err) {
                    reject(err);
                }
                resolve(response.body);
            })
        });
        return res;
    } catch (e) {
        throw new Error('素材上传失败(' + e.response.status + '):' + fileUrl);
    }
}

文章原始链接:https://sijie.wang/posts/NodeJS%E7%94%A8request%E4%B8%8A%E4%BC%A0%E5%9B%BE%E7%89%87%E5%88%B0%E5%BE%AE%E4%BF%A1%E5%85%AC%E4%BC%97%E5%B9%B3%E5%8F%B0%E6%8E%A5%E5%8F%A3/

本站文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请保留原始链接