【问题标题】:Sending data to nodejs server向nodejs服务器发送数据
【发布时间】:2015-03-18 22:00:27
【问题描述】:

我目前正在学习 nodejs,但我遇到了一些事情。 我正在创建一个提供 html 文件的服务器。该 html 文件有一个执行 xmlHttpRequest 来获取数据的 js。我要检索的数据要发送回我的服务器进行处理。最后一步是我卡住的地方。每次服务器停止时,我想在服务器中接收 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);
}

我在浏览器的控制台中得到这个

发布http://127.0.0.1:1337/net::ERR_CONNECTION_REFUSED

这个在节点的cmd中

events.js:72 投掷者; // 未处理的“错误”事件 ^ 错误:EISDIR,读取

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

我也知道我可以使用 express 和其他模块,但是为了学习 node,我正在尝试这样做。所以我希望有人能把我推向正确的方向。

【问题讨论】:

  • 看起来您的服务器没有捕获 ajax URL 的路由,不管是什么?
  • 你能解释一下吗?
  • 当您向 URL 发送 POST 数据时,服务器必须捕获它。您将其发送到/,并且您有一个捕获所有内容的服务器,但它似乎没有执行任何操作或返回任何内容,可能更像这样 -> jsfiddle.net/5eeLn17o
  • @adeneo 您能否将其发布为答案,以便我接受?因为你的 sn-p 真的帮助了我。您能否通过将数据发送回我的客户(我的问题的第二部分)将我推向正确的方向?在处理 url 时,我正在计算以显示处理的数量 % 并且它正在工作,我只想在我的 html 中输出它。
  • 这有点复杂,使用 ajax 您实际上只能返回一次数据,而不是在请求进行时。您可能必须进行某种长轮询才能在发送百分比时返回百分比,或者使用 websockets,您可以在 ajax 请求发送数据时将百分比发送回浏览器。

标签: javascript node.js xmlhttprequest


【解决方案1】:

events.js:72 throw er; // 未处理的“错误”事件 ^ 错误: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);

【讨论】:

  • 我也实现了你的 sn-p,但我将资源解释为样式表,但使用 MIME 类型文本/纯文本传输:“127.0.0.1:1337/css/style.css”。和 js 一样。我究竟做错了什么?因为我怎么看,好像还不错??
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 2010-12-03
  • 1970-01-01
相关资源
最近更新 更多