我有读取文件“example.js”并将其发送到客户端的代码。
app.get('/mods/example.js', function(req, res) {
fs.readFile('./mods/example.js',
{encoding: 'utf-8'},
(err, data) => {
if (!err)
{
res.send("var example = new Mod();" + data);
}
});
});
问题是如何将响应作为 JavaScript 文件发送?
当我在网络浏览器中打开该文件时,它是一个 html 文件而不是 javascript 文件。
提前致谢!
最佳答案
根据noisypixy的建议,我使用了res.type
函数来更改对javascript的响应类型。
res.type('.js');
res.send("var john = new Human();");
还有很多其他文件类型,例如 html
、json
、png
。
带有示例代码的 API 引用:http://expressjs.com/en/4x/api.html#res.type
关于javascript - Node.js Express 如何以 javascript 或其他文件类型发送响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41410660/