如何使用正确的 mimetype 而不是 text/plain 提供 JSON 文件?

How do I serve JSON files with proper mimetype and not text/plain?

我正在尝试使用 manifest.json 文件,如果类型未设置为 application/json,该文件将无法工作。

我有一个 nginx 服务器 运行 node/express.

我将 manifest.json 放入我的 public 文件夹中,服务器将类型读取为 text/plain,并抛出错误。

/etc/nginx/config/下已经有一行内容为:

application/json                      json;

我什至尝试使用 express 提供文件并指定 header:

var manifest = fs.readFileSync('routes/manifest.json', 'utf8');
router.get('/manifest.json', function(req, res) {
    res.header("Content-Type", 'application/json');
    res.json(manifest);
});

而且仍然读作 text/plain。

我猜这是我需要用 nginx 做的事情,但我发现的所有建议都在谈论我没有的文件。

fs 模块读取您现有的 manifest.json 文件时,它会将其转换为一个大的 utf-8 字符串,而不是实际的 JSON.

在人眼中,它看起来像普通的JSON,但实际上只是字符串中的一堆JSON。

对于服务器,它只看到字符串并设置 mime 类型,如 text/plain,因为它在技术上是。

您可以尝试将 res.json(manifest); 替换为 res.send(JSON.parse(manifest));,这应该采用 fsmanifest.json 获得的值,并尝试将其转换为正确格式的 JSON 使用正确的 mime 类型。