gpt4 book ai didi

node.js - http ://localhost:8080/is not working

转载 作者:IT老高 更新时间:2023-10-28 23:18:02 25 4
gpt4 key购买 nike

我是 nodeJS 的新手,并试图学习它。
我正在尝试从 http://net.tutsplus.com/tutorials/javascript-ajax/node-js-for-beginners/ 执行 hello world 示例但我没有得到任何输出,并且在 chrome 浏览器上没有收到数据页面。
我已经在我的 PC 上安装了 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);

最佳答案

我想您使用 Node 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);

关于node.js - http ://localhost:8080/is not working,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19608330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com