1.根据文档,我们需要获取当前项目的

AppID(小程序ID)
AppSecret(小程序密钥)

在微信开发平台
寻找即可找到


接下来我在项目目录中创建一个
config.js

里面的内容填自己的数据即可

这里我们使用第三方进行辅助
<mark>cnpm i -S request requset-promise</mark>

成功后,返回index.js内进行引入操作

const config=require('../config.js')
const request =require('request-promise')
const fs=require('fs')

然后进行请求操作

try {
    let options = {
      uri: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.appid + '&secret=' + config.secret + '',
      json: true
    }
    let { access_token } = await request(options)
    console.log(access_token);
  } catch (err) {
    console.log(err);
  }

接下来对本地3000端口进行上传操作
拿到
access_token

官方定义获取access_token文档

然后我们就可以发送post请求了
官方定义http_api上传文档

在官方文档中,我们可以看到

所以按照官方文档编写index.js内部的代码

router.post('/uploadBannerImg', async (ctx, next) => {
  var files = ctx.request.files;
  var file = files.file;
  try {
    let options = {
      uri: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + config.appid + '&secret=' + config.secret + '',
      json: true
    }
    let { access_token } = await request(options)
    let fileName = `${Date.now()}.jpg`;
    let filePath = `banner/${fileName}`;
    options = {
      method: 'POST',
      uri: 'https://api.weixin.qq.com/tcb/uploadfile?access_token=' + access_token + '',
      body: {
        "env": 'ahf-oz31v',//服务器名
        "path": filePath,
      },
      json: true,
    }
    options = {
      method: 'POST',
      uri: res.url,
      formData: {
        "Signature": res.authorization,
        "key": filePath,//服务器内将要生成的文件路径
        "x-cos-security-token": res.token,
        "x-cos-meta-fileid": res.cos_file_id,
        "file": {
          value: fs.createReadStream(file.path),
          options: {
            filename: fileName,
            contentType: file.type
          }
        }
      }
    }
    await request(options)
    ctx.body = res;
  } catch (err) {
    console.log(err);
  }
})

module.exports = router


        }
      }
    }

最后~~~
成功

注意

如果你确认代码正确但还是失败,那么请多刷新几次