我是nodeJS和triyng的新手来学习它
我试图从http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/执行hello world示例
但我没有得到任何输出,我得到铬浏览器没有收到数据页面。
我在我的电脑上安装了apache(XAMPP),但是它没有激活,当我试图在终端中运行node http.js
时,我没有得到任何输出。
我有另一个文件,hello.js,其中包含console.log('Hello World!');
当我运行node hello.js
时,我在终端输出Hello World!
。
但http.js
无效。
http.js代码:
// 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 on the 8080 port.
}).listen(8080);
答案 0 :(得分:27)
我想您使用节点0.10.x或更高版本?它在stream
api中有一些变化,通常称为Streams2。 Streams2的一个新功能是,在您完全使用流(即使它是空的)之前,end
事件永远不会被触发。
如果您确实想要在end
事件上发送请求,则可以使用Streams 2 API来使用该流:
var http = require('http');
http.createServer(function (request, response) {
request.on('readable', function () {
request.read(); // throw away the data
});
request.on('end', function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
或者您可以将流切换为旧(流动)模式:
var http = require('http');
http.createServer(function (request, response) {
request.resume(); // or request.on('data', function () {});
request.on('end', function () {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
});
}).listen(8080);
否则,您可以立即发送回复:
var http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {
'Content-Type': 'text/plain'
});
response.end('Hello HTTP!');
}).listen(8080);
答案 1 :(得分:4)
试试这个
//Lets require/import the HTTP module
var http = require('http');
//Lets define a port we want to listen to
const PORT=8080;
//We need a function which handles requests and send response
function handleRequest(request, response){
response.end('It Works!! Path Hit: ' + request.url);
}
//Create a server
var server = http.createServer(handleRequest);
//Lets start our server
server.listen(PORT, function(){
//Callback triggered when server is successfully listening. Hurray!
console.log("Server listening on: http://localhost:%s", PORT);
});