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

Roh*_*yas 2 export-to-excel node.js express amazon-mws node-fetch

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

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

您可以在附件中看到下载的excel文件。在此输入图像描述

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

Roh*_*yas 5

最后,我得到了一个解决方案。我更改了调用 API 的方法,如下所示,并获得了正确的 excel 文件。

我使用了node-fetch,然后通过node-fetch向Amazon 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;
}
Run Code Online (Sandbox Code Playgroud)