大家好,我今天刚开始学习 node.js,在网上搜索了很多东西,然后尝试在 node.js 中编写代码,我使用这两个代码显示相同的结果,但最后一个显示错误在我的浏览器上出现“找不到页面”之类的内容。所以请解释一下为什么?
// JScript source code
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');
这是可行的,但是
// Include http module.
var http = require("http");
// Create the server. Function passed as parameter is called on every request made.
// request variable holds all request parameters
// response variable allows you to do anything with response sent to the client.
http.createServer(function (request, response) {
// Attach listener on end event.
// This event is called when client sent all data and is waiting for response.
request.on("end", function () {
// Write headers to the response.
// 200 is HTTP status code (this one means success)
// Second parameter holds header fields in object
// We are sending plain text, so Content-Type should be text/plain
response.writeHead(200, {
'Content-Type': 'text/plain'
});
// Send data and end response.
response.end('Hello HTTP!');
});
}).listen(1337, "127.0.0.1");
这个不行
为什么?
最后一个失效的链接 http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/ 感谢您的所有答案,但我仍然不明白这些问题。 最后一个不工作的只是 request.on?
最佳答案
request
是 http.IncomingMessage
的一个实例,它实现了 stream.Readable
接口(interface)。
文档位于 http://nodejs.org/api/stream.html#stream_event_end说:
Event: 'end'
This event fires when no more data will be provided.
Note that the end event will not fire unless the data is completely consumed. This can be done by switching into flowing mode, or by calling
read()
repeatedly until you get to the end.var readable = getReadableStreamSomehow(); readable.on('data', function(chunk) { console.log('got %d bytes of data', chunk.length); }) readable.on('end', function() { console.log('there will be no more data.'); });
所以在你的情况下,因为你不使用 read()
或订阅 data
事件,end
事件将永远不要开火。
添加
request.on("data",function() {}) // a noop
在事件监听器中可能会使代码工作。
请注意,仅当 HTTP 请求具有正文时才需要将请求对象用作流。例如。用于 PUT 和 POST 请求。否则你可以认为请求已经完成,然后发送数据。
如果您发布的代码是从其他网站直接获取的,则该代码示例可能基于 Node 0.8。在 Node 0.10 中,流的工作方式发生了变化。
来自 http://blog.nodejs.org/2012/12/20/streams2/
WARNING: If you never add a 'data' event handler, or call resume(), then it'll sit in a paused state forever and never emit 'end'. So the code you posted would have worked on Node 0.8.x, but does not in Node 0.10.x.
关于javascript - 我在 node.js 中的 http.createserver 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19363439/