将数据发送到nodejs服务器

时间:2015-03-18 22:00:27

标签: javascript node.js xmlhttprequest

我现在正在学习nodejs,而且我遇到了一些问题。 我正在创建一个服务于html文件的服务器。该html文件有一个js,它执行xmlHttpRequest来获取数据。我检索的数据我想发送回我的服务器来处理它。最后一步是我被困的地方。每次服务器停止时,我都希望收到服务器中的URL来处理它们。

Server.js

var http = require('http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');

var mimeTypes = {
    "html": "text/html",
    "js": "text/javascript",
    "css": "text/css"};

    http.createServer(function(request, response){

        var uri = url.parse(request.url).pathname;
        var filename = path.join(process.cwd(), uri);

        fs.exists(filename, function(exists){
            if(!exists){
                console.log(filename + " does not exist");
                response.writeHead(200, {'Content-Type' : 'text/plain'});
                response.write('404 Not found\n');
                response.end();
                return;
            }

            var mimeType = mimeTypes[path.extname().split(".")[1]];
            response.writeHead(200, {'Content-Type' : mimeType});

            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(response);
        });

    response.on('end', function(){
        console.log("Request: " + request);
        console.log("Response: " + response);
    });

    }).listen(1337);

Client.js

function getURLs(){
    var moduleURL = document.getElementById("url").value;
    var urls = [];
    console.log(moduleURL);

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
      if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var xml = xmlhttp.responseXML;
            var items = xml.children[0].children[0].children;

            for(var i = 13; i<items.length; i++){
                urls.push(items[i].children[1].getAttribute("url")+"&hd=yes");
            }

            //console.log(urls);
            sendDataToServer(urls);
        }
      }
    xmlhttp.open("GET", moduleURL, true); 
    xmlhttp.send();

}

function sendDataToServer(urls){
    //console.log(urls);

    var http = new XMLHttpRequest();
    http.open("POST", "http://127.0.0.1:1337/", true);
    http.send(urls);
}

我在浏览器的控制台中获取此内容

  

POST http://127.0.0.1:1337/ net :: ERR_CONNECTION_REFUSED

这是在节点的cmd中

  

events.js:72           扔掉//未处理的错误&#39;事件                 ^错误:EISDIR,阅读

在处理数据的同时,我想将进度发送回客户端,以便在最终用户的html页面上显示。我已经具备了进度的功能,它只是发送/接收我遇到的数据。有人能指出我正确的方向吗?

我也知道我可以使用快速和其他模块,但要学习节点我尝试这样做。所以我希望有人能把我推向正确的方向。

1 个答案:

答案 0 :(得分:0)

  

events.js:72 throw er; //未处理的错误&#39;事件^错误:EISDIR,阅读

此错误表示您尝试阅读的文件实际上是一个目录。

您需要做的是确保该文件确实是一个文件,因为函数 fs.exists()仅用于文件。

在此示例中,fs.lstat()用于获取fs.stat对象,该对象具有确保文件类型正确所需的方法。

var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');

var mimeTypes = {
    "html": "text/html",
    "js": "text/javascript",
    "css": "text/css"
};

http.createServer(function(request, response){

    var uri = url.parse(request.url).pathname;
    var filename = path.resolve(path.join(process.cwd(), uri));
    console.log(filename);

    // Get some information about the file
    fs.lstat(filename, function(err, stats) {

      // Handle errors
      if(err) {
        response.writeHead(500, {'Content-Type' : 'text/plain'});
        response.write('Error while trying to get information about file\n');
        response.end();
        return false;
      }

      // Check if the file is a file.
      if (stats.isFile()) {

        fs.exists(filename, function(exists){
            if(!exists){
                console.log(filename + " does not exist");
                response.writeHead(200, {'Content-Type' : 'text/plain'});
                response.write('404 Not found\n');
                response.end();
                return;
            }

            var mimeType = mimeTypes[path.extname().split(".")[1]];
            response.writeHead(200, {'Content-Type' : mimeType});

            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(response);
        });

      } else {
        // Tell the user what is going on.
        response.writeHead(404, {'Content-Type' : 'text/plain'});
        response.write('Request url doesn\'t correspond to a file. \n');
        response.end();
      }

    });

response.on('end', function(){
    console.log("Request: " + request);
    console.log("Response: " + response);
});

}).listen(1337);
相关问题