微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从 AWS MWS API json 响应下载 .xlsx 文件?

如何解决如何从 AWS MWS API json 响应下载 .xlsx 文件?

我正在使用 Express JS server 来执行 AWS MWS API。根据 MWS 文档,_GET_REMOTE_FULFILLMENT_ELIGIBILITY_ 返回 excel 文件对象。

我在 node js 中创建了 API,但我无法获得正确的 excel。我在下载的 excel 文件中有奇怪的字符。

您可以在附件中看到下载的 excel 文件

enter image description here

const getRemoveFulfillmentEligibilityDataCon = async(req,res) => {
  const mwsRequestData = {
    Version: '2009-01-01',Action: 'GetReport','SellerId': 'MWS_SELLER_ID','MWSAuthToken': 'MWS_AUTH_TOKEN',ReportId: 'XXXXXXXXXXXXXX',};
 
  try {
    const response = await amazonMws.reports.search(mwsRequestData);
   

    /* make the worksheet */
    var ws = XLSX.utils.json_to_sheet(response.data);
    var wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb,ws);
    
    XLSX.writeFile(wb,"sheetjs.xlsx");
   
    return response;
    

  } catch (error) {
    console.log('error ',error);
    return error;
  }
}

解决方法

终于找到了解决办法。我改变了我的方法来调用 API,如下所示,我得到了一个正确的 excel 文件。

我使用了 node-fetch,然后通过 node-fetch 向亚马逊 MWS 发送请求。

node-fetch 正确解码内容编码 (gzip/deflate) 并自动将字符串输出转换为 UTF-8。

var param = {};
  param['AWSAccessKeyId']   =  'xxxxxxxxxxxxx'; 
  param['Action']           = 'GetReport';
  param['MarketplaceId']    =  'xxxxxxxxxxxxx'; 
  param['SellerId']         =  'xxxxxxxxxxxxx'; 
  param['ReportId']         =  'xxxxxxxxxxxxx'; 
  param['ItemCondition']    = 'New'; 
  param['SignatureMethod']  = 'HmacSHA256';  
  param['SignatureVersion'] = '2'; 
  param['Timestamp']        = encodeURIComponent(new Date().toISOString());
  param['Version']          = '2009-01-01'; 
  secret = 'xxxxxxxxxxxxx'; 

  var url = [];

  for(var i in param){
    url.push(i+"="+param[i])
  }

  url.sort();
  var arr = url.join("&");

  
  var sign  = 'POST\n'+'mws.amazonservices.com\n'+'/Reports/2009-01-01\n'+arr;

  const crypto = require('crypto');
  let s64 = crypto.createHmac("sha256",secret).update(sign).digest('base64');

  let signature = encodeURIComponent(s64);

  var bodyData = arr+"&Signature="+signature;

  const fileName = "sheetjs.xlsx";

  var apiResponse = await fetch('https://mws.amazonservices.com/Reports/2009-01-01',{
    method: 'POST',body: bodyData,headers: {
      'content-type': 'application/x-www-form-urlencoded','Accept': '',},})
  .then(res => {
    const dest = fs.createWriteStream('./'+fileName);
    res.body.pipe(dest).on('finish',function(){
      //console.log('done');
      return {'Status': 200,'Message': 'Downloaded'};
    });
    
  })
  .catch(error => {
     console.log('Request failed',error);
  });
  
  
  return apiResponse;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。