Dav*_*nan 0 javascript response node.js express
我有读取文件“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);
}
});
});
Run Code Online (Sandbox Code Playgroud)
问题是如何将响应作为 javascript 文件发送?
当我在网络浏览器中打开文件时,它是一个 html 文件,而不是一个 javascript 文件。
提前致谢!
正如noisepixy 所建议的,我使用该res.type函数将响应的类型更改为javascript。
res.type('.js');
res.send("var john = new Human();");
Run Code Online (Sandbox Code Playgroud)
还有许多其他文件类型,例如html, json, png.
API 参考示例代码:http : //expressjs.com/en/4x/api.html#res.type