首页 > 解决方案 > TypeError:标头内容包含无效字符

问题描述

下面是我用sailsJS从我的服务器获取文件的函数。当我尝试运行此函数时,我的控制台向我抛出了这种类型的错误: TypeError: The header content contains invalid characters

在邮递员中,我以 pdf 格式发送文件,

content-type 应该怎么看这里?

fn: async function ({ id }, exits) {

    this.res.set('Content-disposition', `attachment; filename=${id}`, 'content-type', 'application/pdf')//here
    this.res.set('Access-Control-Allow-Origin', '*')

    const localPath = path.join(sails.config.custom.uploadDirectory, id)

    this.res.sendFile(localPath);
  }

以及如何在浏览器中打开文件而不是将他下载到桌面?

提前致谢

标签: javascriptnode.js

解决方案


根据此处的 SailJS 文档,您可以传入单个对象参数(标头)来一次设置多个标头字段,其中keys是标头字段名称,对应values的是所需的值。

我认为您没有以正确的方式设置标题值。

如果设置多个值,它应该发送完整的对象:

res.set({
  'Content-disposition': 'attachment',
  'content-type': 'application/pdf',
  'filename':  'filename.pdf'
})

[编辑]:为了在浏览器中打开文件,您应该添加

Content-Disposition: `inline;filename="${id}"`

推荐阅读