使用nodejs

时间:2015-07-17 15:03:21

标签: node.js server

(我遵循教程的所有内容)

我尝试使用nodejs在我的计算机中创建一个基本服务器,代码如下:

var http = require('http');

function onRequest(request, response){
console.log("A user made a request" + request.url);
response.write(200, {"Context-Type":"text/plain"});
response.write("Here is data");
response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server is now running.....");

我去网站输入localhost:8888,结果如下:

C:\ Program Files \ nodejs \ nodejs> node server.js 服务器正在运行..... 用户发出请求/ _http_outgoing.js:433     抛出新的TypeError('第一个参数必须是字符串或缓冲区');           ^ TypeError:第一个参数必须是字符串或Buffer     在ServerResponse.OutgoingMessage.write(_http_outgoing.js:433:11)     在Server.onRequest(C:\ Program Files \ nodejs \ nodejs \ server.js:5:11)     在Server.emit(events.js:110:17)     在HTTPParser.parserOnIncoming [as oncoming](_http_server.js:491:12)     在HTTPParser.parserOnHeadersComplete(_http_common.js:111:23)     在Socket.socketOnData(_http_server.js:343:22)     在Socket.emit(events.js:107:17)     在readableAddChunk(_stream_readable.js:163:16)     在Socket.Readable.push(_stream_readable.js:126:10)     在TCP.onread(net.js:538:20)

网页上说该网页不可用。 有什么问题?

1 个答案:

答案 0 :(得分:0)

您没有正确地编写头部,您应该使用http方法writeHead。像这样:

var http = require('http');

function onRequest(request, response){
    console.log("A user made a request" + request.url);

    //Here is your mistake, you have "write" instead of "writeHead" and I think you should use "Content" instead of "Context"
    response.writeHead(200, {"Content-Type":"text/plain"});

    response.write("Here is data");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server is now running.....");