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

标签 node.js express export-to-excel amazon-mws node-fetch

我正在使用 Express JS 服务器 执行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向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;
}

关于node.js - 如何从AWS MWS API json响应下载.xlsx文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67786734/

相关文章:

javascript - Node JS 同步数据库调用

node.js - 如何在具有 yarn 工作空间的 monorepo 中从 nodejs 项目构建 docker 镜像

python - 使用 xlsxwriter 写入单元格时是否可以应用多种单元格格式?

node.js - 如何为模块使用外部 .d.ts

node.js - 2023年如何在nodejs中使用gmail发送电子邮件?

html - Webpack:使用组件特定的 css 在 html 中呈现不同?

jsf - java.lang.NoClassDefFoundError : org/apache/poi/ss/usermodel/RichTextString at org. primefaces.component.export.ExporterFactory.getExporterForType

javascript - wait 仅在异步函数和模块的顶级主体中有效,因为它在顶级主体中

node.js - 如何让 Stylus 与 CoffeeScript 中的 Express 和 Connect 一起工作

php - 如何调整单元格的宽度,使其不会在 Spreadsheet_Excel_Writer 中剪切单词