【问题标题】:Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file downloadNode.js res.setHeader('content-type', 'text/javascript');将响应 javascript 作为文件下载推送
【发布时间】:2013-04-09 10:20:21
【问题描述】:

场景:考虑以下代码以提供 JavaScript 作为来自 Node.JS 服务器的响应。

var http = require('http');

http.createServer(function (req, res) {
var JS_Script = 'function Test() { alert("test success")}';
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
}).listen(8811);

问题:强制浏览器下载文件。

问题:如何让它在浏览器上呈现?

注意:在 .net 网络服务中使用相同的 HTTP-header: 'content-type', 'text/javascript'

因此,其明确的以下陈述并不成立。
如果您希望 Web 浏览器呈现 HTML,则应将其更改为:

Content-Type: text/html

更新:在下载过程中检查content-typeapplication/octet-stream

但是当我用curl点击请求时,输出如下:

C:\>curl -is http://localhost:8811/
HTTP/1.1 200 OK
Content-Type: text/javascript
Content-Length: 166
Date: Tue, 09 Apr 2013 10:31:32 GMT
Connection: keep-alive

function Test() { alert("test success")}

【问题讨论】:

  • res.send() 是 Express-ism,当您使用普通的 http 时不可用。所以我认为你的示例代码并不是你实际使用的 100%。
  • 使用application/javascript作为内容类型

标签: node.js


【解决方案1】:

使用application/javascript 作为内容类型而不是text/javascript

text/javascript 被提及已过时。见参考docs

http://www.iana.org/assignments/media-types/application

也可以在 SO 上查看这个问题。

更新:

我已尝试执行您提供的代码,但以下代码不起作用。

res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);

这对我有用。

res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);

正如robertklep所建议的,请参考node http docs,那里没有response.send()

【讨论】:

  • setHeader 甚至没有受到尊重,所以还有其他事情发生。
【解决方案2】:

您可以直接设置内容类型如下:

res.writeHead(200, {'Content-Type': 'text/plain'});

参考nodejs文档link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 2013-12-06
    • 2014-06-15
    • 2012-04-20
    • 2015-09-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多