【问题标题】:Getting encoded characters as a response获取编码字符作为响应
【发布时间】:2021-06-01 17:08:23
【问题描述】:

网址:http://www.africau.edu/images/default/sample.pdf

我想请求上述 URL 并获取 PDF 文件作为响应,当我在 postman 或 insomnia 中执行此操作时,我可以看到输出为 PDF。但是,当我尝试使用代码时,我在前端得到了垃圾值

var axios = require("axios").default;
var options = {method: 'GET', url: 'http://www.africau.edu/images/default/sample.pdf'};

axios.request(options).then(function (response) {
  res.send(response.data);
}).catch(function (error) {
  console.error(error);
});

我得到的输出

%PDF-1.3 %���� 1 0 obj << /Type /Catalog /Outlines 2 0 R /Pages 3 0 R >> endobj 2 0 obj << /Type /Outlines /Count 0 >> endobj 3 0 obj << /Type /Pages /Count 2 /Kids [ 4 0 R 6 0 R ] >> endobj 4 0 obj << /Type /Page /Parent 3 0 R /Resources << /Font << /F1 9 0 R >> /ProcSet 8 0 R >> /MediaBox [0 0 612.0000 792.0000] /Contents 5 0 R >> endobj 5 0 obj << /Length 1074 >> stream 2 J BT 0 0 0 rg /F1 0027 Tf 57.3750 722.2800 Td ( A Simple PDF File ) Tj ET BT /F1 0010 Tf 69.2500 688.6080 Td ( This is a small demonstration .pdf file - ) Tj ET BT /F1 0010 Tf 69.2500 664.7040 Td ( just for use in the Virtual Mechanics tutorials. More text. And more ) Tj ET BT /F1 0010 Tf 69.2500 652.7520 Td ( text. And more text. And more text. And more text. ) Tj ET BT /F1 0010 Tf 69.2....

预期输出

【问题讨论】:

  • 请去掉正则表达式标签,这与正则表达式无关
  • @PeterThoeny 对不起,先生,感谢您告诉我。
  • 嗨@uingtea, res.send() 会将HTTP响应发送到前端

标签: javascript node.js express axios


【解决方案1】:

如果您将Content-Type 标头设置为application/pdf,文件将正常显示。

const axios = require("axios").default;
const options =  { 
    method: 'GET',
    url: 'http://meltwaternews.com/ext/mediac/311919964.pdf',
    responseType: "arraybuffer"
};

axios.request(options).then(function (response) {
    res.header('Content-Type', 'application/pdf');
    res.send(response.data);
}).catch(function (error) {
    console.error(error);
});

我已更新答案以确保我们获得“arraybuffer”的 responseType,请参阅 https://github.com/axios/axios#request-config 上的 axios 文档

【讨论】:

  • 嗨@Terry,感谢您对此进行调查,实际上它适用于少数PDF文件。但是,它只会显示其他几个链接的空白幻灯片,如下面meltwaternews.com/ext/mediac/311919964.pdf
  • 嗨@RAJENDRAH,我已经更新了我的答案,以确保我们得到一个二进制响应。现在应该可以了。
  • 嗨@Terry,非常感谢你的兄弟,你真的救了我的命,愿上帝保佑你。
  • 太好了,很高兴能帮上忙!祝你有美好的一天! ?
猜你喜欢
  • 1970-01-01
  • 2015-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多