Node.js res.setHeader('content-type', 'text/javascript'); 将响应 javascript 作为文件下载推送
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15899357/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download
提问by Amol M Kulkarni
Scenario: Consider the following code to give a JavaScript as a response from the Node.JS server.
场景:考虑以下代码,将 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.end(JS_Script);
}).listen(8811);
Issue: It forcing the browser to download the file.
问题:它强制浏览器下载文件。
Question: How can I make it to render on browser?
问题:如何让它在浏览器上呈现?
Note: Working in .net web service with same HTTP-header: 'content-type', 'text/javascript'
注意:在 .net 网络服务中使用相同的HTTP-header: 'content-type', 'text/javascript'
So, Its clear following statement does not hold good.
If you want a web browser to render the HTML, you should change this to:
因此,其明确的以下陈述并不成立。
如果您希望 Web 浏览器呈现 HTML,则应将其更改为:
Content-Type: text/html
Update: On inspecting the content-typeduring the download its application/octet-stream
更新:在content-type下载过程中检查其application/octet-stream
But the same when I hit a request with curl, the following is the output:
但是当我用 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")}
回答by mithunsatheesh
Use application/javascriptas content type instead of text/javascript
使用application/javascript的内容类型,而不是text/javascript
text/javascriptis mentioned obsolete. See reference docs.
text/javascript提到过时了。请参阅参考文档。
http://www.iana.org/assignments/media-types/application
http://www.iana.org/assignments/media-types/application
Also see this question on SO.
另请参阅SO上的此问题。
UPDATE:
更新:
I have tried executing the code you have given and the below didn't work.
我已尝试执行您提供的代码,但以下不起作用。
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
This is what worked for me.
这对我有用。
res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);
As robertklep has suggested, please refer to the node http docs, there is no response.send()there.
正如 robertklep 所建议的,请参考节点 http docs,那里没有response.send()。

