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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:09:46  来源:igfitidea点击:

Node.js res.setHeader('content-type', 'text/javascript'); pushing the response javascript as file download

node.js

提问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()

回答by Vaishali Tekale

You can directly set the content type like below:

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

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

For reference go through the nodejs Docs link.

参考通过 nodejs 文档链接