我在node.js中的http.createserver不起作用?
你好,我今天刚开始学习node.js,并在互联网上search了很多东西,然后尝试在node.js中编码,我使用这两个代码来显示相同的结果,但最后一个是在我的浏览器上显示错误东西喜欢“无法find页面”。所以请向我解释为什么?
// 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
接口。
http://nodejs.org/api/stream.html#stream_event_end上的文档说:
事件:'结束'
这个事件在没有更多数据提供的时候触发。
请注意,除非数据完全消耗,否则结束事件不会触发。 这可以通过切换到stream动模式,或通过重复调用
read()
直到完成。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请求具有主体时,才需要使用请求对象作为stream。 例如,对于PUT和POST请求。 否则,你可以考虑已经完成的请求,只是发送数据。
如果您发布的代码是从其他网站上直接获取的,则可能是此代码示例基于节点0.8。 在节点0.10中,stream的工作方式发生了变化。
来自http://blog.nodejs.org/2012/12/20/streams2/
警告:如果你永远不会添加一个'数据'事件处理程序,或者调用resume(),那么它将永远处于暂停状态,永远不会发出'结束'。 所以你发布的代码将在Node 0.8.x上工作,但不在Node 0.10.x中。
您应用于HTTP服务器的函数是requestListener
,它提供两个参数request
和response
,它们分别是http.IncomingMessage
和http.ServerResponse
实例。
http.IncomingMessage
类从底层可读stream中inheritanceend
事件。 可读stream不处于stream动模式,所以结束事件永远不会触发,从而导致响应永远不会被写入。 由于请求处理程序运行时响应已经可写,因此可以直接写入响应。
var http = require('http'); http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello HTTP!'); }).listen();