node.js / get request&在http模块中定义根文件夹

时间:2013-07-13 13:28:00

标签: node.js

我定义了下一个http请求:

var http = require("http");
http.get("http://localhost:8001/pro.html", function(respond) {
    check();}).on('error', function(e) {
  console.log("Got err: " + e.message);
});

现在,在服务器端,我定义了下一个:

var server = net.createServer(function(socket) {
// Some code
socket.on('data', function(d) {
var t = http.request(d, function (res){
            console.log(d);
            console.log(res.statusCode);
        });
// Some code}

我有两个问题:

  1. 什么都没打印出来。为什么它没有到达console.log(d);console.log(res.statusCode);
  2. Pro.html位于c://myFolder。我如何告诉我的服务器这个页面的位置?
  3. 谢谢。

1 个答案:

答案 0 :(得分:0)

看起来您正在尝试使用低级套接字模块(' net ')来实现HTTP服务器。正确的模块是“ http ”(Node.js HTTP documentation),实现很简单:

您的客户方:

var http = require("http");

http.get("http://localhost:8001/pro.html", function(response)
{
    response.setEncoding("utf8");
    response.on("data", function(data)
    {
        console.log("response:", data);
    });

}).on("error", function(e)
{
    console.log("Got err: " + e.message);
});

对于服务器端:

var http = require("http");

var server = http.createServer(function(request, response)
{
    response.end("Here's your pro page!\n")

}).listen(8001);

请注意,上述功能是一个不切实际的简单服务器,它返回固定响应,而不考虑请求的URL。在任何实际应用程序中,您将使用一些逻辑将请求的URL映射到回调函数(以生成动态内容),静态文件服务器,无所不包的框架(如“表达”)或组合以上。