Sar*_*oon 12 javascript node.js
大家好我刚刚开始学习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/');
Run Code Online (Sandbox Code Playgroud)
这是有效的
// 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");
Run Code Online (Sandbox Code Playgroud)
这个不起作用
为什么?
最后一个不起作用的链接 http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/ 感谢您的所有答案,但我仍然不明白这些问题.最后一个不起作用的是request.on?
Myr*_*tol 13
request是http.IncomingMessage实现stream.Readable接口的实例.
http://nodejs.org/api/stream.html#stream_event_end上的文档说:
事件:'结束'
如果不再提供数据,则会触发此事件.
请注意,除非数据被完全消耗,否则不会触发结束事件.这可以通过切换到流动模式,或通过
read()反复调用直到你到达结束来完成.Run Code Online (Sandbox Code Playgroud)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
Run Code Online (Sandbox Code Playgroud)
在事件监听器内可能会使代码工作.
请注意,仅在HTTP请求具有正文时才需要将请求对象用作流.例如,PUT和POST请求.否则,您可以考虑已经完成的请求,并发送数据.
如果您的发布的代码是从其他网站直接获取的,则可能是此代码示例基于Node 0.8.在节点0.10中,流的工作方式发生了变化.
来自http://blog.nodejs.org/2012/12/20/streams2/
警告:如果您从未添加"数据"事件处理程序或调用resume(),那么它将永远处于暂停状态并且永远不会发出"结束".因此,您发布的代码将在Node 0.8.x上运行,但不在Node 0.10.x中.
hex*_*ide 10
您应用于HTTP服务器的功能是requestListener提供两个参数request,和response,它们分别是http.IncomingMessage和的实例http.ServerResponse.
该类从底层可读流http.IncomingMessage继承end事件.可读流不处于流动模式,因此结束事件永远不会触发,因此永远不会写入响应.由于响应在运行请求处理程序时已经可写,因此您可以直接写入响应.
var http = require('http');
http.createServer(function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/plain'
});
res.end('Hello HTTP!');
}).listen();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20628 次 |
| 最近记录: |