簡體   English   中英

將數據發送到Node.js服務器

[英]Sending data to nodejs server

目前,我正在學習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);
}

我在瀏覽器的控制台中得到這個

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

而這在節點的cmd中

events.js:72 throw er; //未處理的“錯誤”事件^錯誤:EISDIR,已讀取

在處理數據時,我想將進度發送回客戶端,以在最終用戶的html頁面上顯示。 我已經具有進度功能,只是卡住了我的數據的發送/接收。 有人可以指出我正確的方向嗎?

我也知道可以使用express和其他模塊,但是要學習節點,我正在嘗試以這種方式進行。 因此,我希望有人可以將我推向正確的方向。

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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM