公众号开发 调用【上传图文消息内的图片获取URL】接口时,返回 412 错误?
发布于 7 年前 作者 lei92 6691 次浏览 来自 问答

我使用 NodeJS 开发,Express 为框架,在调用微信提供的 【上传图文消息内的图片获取URL】 接口时,axios 报错为 Error: Request failed with status code 412,我不清楚我是哪里做的不对。接口说明必须要用 form表单的形式发送,但是 node 并没有前端的 formData 类,我使用了 form-data 这个 npm 包,通过它来实现此功能,http 请求代理我使用的是 axios,相关代码如下,希望能帮助我解决这个问题, 谢谢!

const SWAP_IMAGE_URL = 'https://api.weixin.qq.com/cgi-bin/media/uploadimg';
let form = new FormData();
form.append("media", fs.createReadStream("./hello.jpg"));
let token = await getAccessToken(app_id);
let config = {
  params: { access_token: token.message },
  headers: form.getHeaders()
};
let result = await axios.post(SWAP_IMAGE_URL, form, config); 
console.log(result);
// 我十分确定 URL 和 access_token 都是正常有效的, 请求的头部 content-type 为 multipart/form-data

报错的信息如下:

message: Error: Request failed with status code 412
      at createError (E:\Desktop\WeChat\Develop\myapp\node_modules\axios\lib\core\createError.js:16:15)
      at settle (E:\Desktop\WeChat\Develop\myapp\node_modules\axios\lib\core\settle.js:17:12)
      at IncomingMessage.handleStreamEnd (E:\Desktop\WeChat\Develop\myapp\node_modules\axios\lib\adapters\http.js:236:11)  
      at IncomingMessage.emit (events.js:228:7)
      at endReadableNT (_stream_readable.js:1185:12)
      at processTicksAndRejections (internal/process/task_queues.js:81:21) {
    config: {
      url: 'https://api.weixin.qq.com/cgi-bin/media/uploadimg',
      method: 'post',
      params: [Object],
      data: [FormData],
      headers: [Object],
      transformRequest: [Array],
      transformResponse: [Array],
      timeout: 0,
      adapter: [Function: httpAdapter],
      xsrfCookieName: 'XSRF-TOKEN',
      xsrfHeaderName: 'X-XSRF-TOKEN',
      maxContentLength: -1,
      validateStatus: [Function: validateStatus]
    },
    request: ClientRequest {
      _events: [Object: null prototype],
      _eventsCount: 6,
      _maxListeners: undefined,
      outputData: [],
      outputSize: 0,
      writable: true,
      _last: true,
      chunkedEncoding: true,
      shouldKeepAlive: false,
      useChunkedEncodingByDefault: true,
      sendDate: false,
      _removedConnection: false,
      _removedContLen: false,
      _removedTE: false,
      _contentLength: null,
      _hasBody: true,
      _trailer: '',
      finished: true,
      _headerSent: true,
      socket: [TLSSocket],
      connection: [TLSSocket],
      _header: 'POST /cgi-bin/media/uploadimg?access_token=30_EXkR_41Gro2UV5C6WXucnrGcIadJ_KW75FyneOzXKv_SHwtk7RWv91pvMNIfg_M4GcR0PHZDQitEFeDPrn4t09y_6SP5C2qjm5PNSUTBFTgxyPjtkcdsetGHSlwSABeAAAMUV HTTP/1.1\r\n' +
        'Accept: application/json, text/plain, */*\r\n' +
        'Content-Type: multipart/form-data; boundary=--------------------------115632283931134332760190\r\n' +
        'User-Agent: axios/0.19.2\r\n' +
        'Host: api.weixin.qq.com\r\n' +
        'Connection: close\r\n' +
        'Transfer-Encoding: chunked\r\n' +
        '\r\n',
      _onPendingData: [Function: noopPendingOutput],
      agent: [Agent],
      socketPath: undefined,
      method: 'POST',
      path: '/cgi-bin/media/uploadimg?access_token=30_EXkR_41Gro2UV5C6WXucnrGcIadJ_KW75FyneOzXKv_SHwtk7RWv91pvMNIfg_M4GcR0PHZDQitEFeDPrn4t09y_6SP5C2qjm5PNSUTBFTgxyPjtkcdsetGHSlwSABeAAAMUV',
      _ended: true,
      res: [IncomingMessage],
      aborted: false,
      timeoutCb: null,
      upgradeOrConnect: false,
      parser: null,
      maxHeadersCount: null,
      _redirectable: [Writable],
      [Symbol(kNeedDrain)]: true,
      [Symbol(isCorked)]: false,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    response: {
      [Symbol(isCorked)]: false,
      [Symbol(kOutHeaders)]: [Object: null prototype]
    },
    response: {
      status: 412,
      statusText: 'Precondition Failed',
      headers: [Object],
      config: [Object],
      request: [ClientRequest],
      data: ''
    },
    isAxiosError: true,
    toJSON: [Function]
  }

大概是因为 fs.createReadStream 这里的原因, 但是我想不到更好的办法了, 不清楚怎么办

回到顶部