简体   繁体   English

如何删除JavaScript / node.js中HTTP响应头中的无效字符?

[英]How to remove invalid characters in an HTTP response header in JavaScript/node.js?

I have the following problem: When a client enters a certain URL it receives an .mp3 file back via sendFile() from Express. 我有以下问题:当客户端输入某个URL时,它会通过sendFile()从Express接收.mp3文件。 The name of the file is defined in the response header as follow: 该文件的名称在响应头中定义如下:

var fileName = (JSON.stringify(data.videoTitle).replace(/["']/g, "") + fileType);

headers: {
        'x-timestamp': Date.now(),
        'x-sent': true,
        'Content-type': 'application/octet-stream',
        'Content-Disposition': 'attachment; filename="' + fileName + '"'
    }

The problem is that fileName is fetched from another website and I have no control over what the title of the file will be. 问题是fileName是从另一个网站获取的,我无法控制文件的标题。 So far it was no problem but it just happened to me that a file contained the character ú which lead to the following error: 到目前为止它没有问题,但只是在我身上发现一个文件包含字符ú导致以下错误:

throw new TypeError('The header content contains invalid characters');

This could potentially happen very often as there are many characters that the headers might not like. 这可能经常发生,因为标题可能不喜欢许多字符。 Is there any possibility that I only keep valid characters before setting the header? 在设置标题之前,我是否有可能只保留有效字符? I assume a whitelist approach would be better than a blacklist approach as there are nearly infinite possibilities of invalid characters. 我认为白名单方法比黑名单方法更好,因为无效字符几乎无限可能。

Thank you very much in advance 非常感谢你提前

Here is an extended answer which basically tells you that only a subset of ASCII or ISO-8859-1 is allowed. 这是一个扩展的答案,它基本上告诉您只允许ASCII或ISO-8859-1的子集。

What character encoding should I use for a HTTP header? 我应该为HTTP标头使用什么字符编码?

And here is your solution: transliterate the filename into ASCII characters to make it safe for use in a header value: 这是您的解决方案:将文件名音译为ASCII字符,以便在标头值中使用安全:

https://www.npmjs.com/package/transliteration https://www.npmjs.com/package/transliteration

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM