2015-01-01 2 views
0

html 웹 페이지와 통신하는 서버 (node)를 만들려고합니다. 모든 양쪽에 근무하지만 양쪽을 연결하는 시도 이후, 나는 다음과 같은 매우 불편 오류가 발생했습니다 :창 개체가 인식되지 않습니다.

여기
/home/gaga/js/index.js 
window.onload = setTimeout(mainFile.start, 1); 
^ 
ReferenceError: window is not defined 

가하는 index.js입니다 :

여기
var Message={}; 
var serv = "localhost:1337"; 

Message.start = function() { 
    document.addEventListener("click", Message.click); 
    document.addEventListener("change", Message.onChange); 
    Message.getStatus(); 
}; 

Message.click = function (ev) { 
    var src = ev.target; 

    if (src.has_class("navbar-brand")) { 
     window.location.reload(); 
    } else if (src.has_class("btn-confirm-registration")) { 
     Message.register(); 
    } else if (src.has_class("btn-register")) { 
     Message.confirmRegistrationInputDisplay(); 
    } else if (src.has_class("btn-login")) { 
     Message.login(); 
    } else if (src.has_class("btn-send-file")) { 
     Message.sendFile(); 
    } else if (src.has_class("btn-success")) { 
     Message.cleanUploadInfo(); 
    } else if (src.has_class("btn-failure")) { 
     Message.cleanUploadInfo(); 
    } else { 
     console.log("else"); 
    } 
}; 

Message.onChange = function (ev) { 
    var src = ev.target; 

    if(src.has_class("input-upload")) { 
     Message.displayInputFile(src); 
    } else { 
     console.log("onChange-else"); 
    } 

} 

Message.register = function() { 
    var logIn = document.getElementsByClassName("login-input")[0]; 
    var pswIn = document.getElementsByClassName("password-input")[0]; 

    if (pswIn.value != "" && logIn.value != "") { 
     logIn.remove_class("alert-danger"); 
     pswIn.remove_class("alert-danger"); 

     var registrationModule = document.getElementsByClassName("confirm-registration")[0]; 
     registrationModule.innerHTML = "<input type=\"password\" class=\"input confirm-password-input form-control\" style=\"width: 150px; display: inline; margin-left: 160px;\" placeholder=\"Confirm password...\"></input><button class=\"btn btn-primary btn-confirm- registration\">Confirm Registration</input>"; 
    } else { 
     logIn.add_class("alert-danger"); 
     pswIn.add_class("alert-danger"); 
    } 
} 

Message.checkPasswords = function() { 
    var logIn = document.getElementsByClassName("login-input")[0]; 
    var pswIn = document.getElementsByClassName("password-input")[0]; 
    var pswConf = document.getElementsByClassName("confirm-password-input")[0]; 

    if (pswIn.value == pswConf.value && pswIn.value != "" && logIn.value != "") { 
     pswConf.remove_class("alert-danger"); 
     pswIn.remove_class("alert-danger"); 
     logIn.value = ""; 
     pswIn.value = ""; 
     return 1; 
    } else { 
     pswConf.add_class("alert-danger"); 
     pswIn.add_class("alert-danger"); 
     return 0; 
    } 
} 

Message.login = function() { 
    var logIn = document.getElementsByClassName("login-input")[0]; 
    var pswIn = document.getElementsByClassName("password-input")[0]; 

    if (pswIn.value != "" && logIn.value != "") { 
     logIn.remove_class("alert-danger"); 
     pswIn.remove_class("alert-danger"); 
     //here send request 
     logIn.value = ""; 
     pswIn.value = ""; 
    } else { 
     logIn.add_class("alert-danger"); 
     pswIn.add_class("alert-danger"); 
    } 
} 

Message.sendFile = function() {//todo: arnaud 
    var sendFile = document.getElementsByClassName("doc-input")[0]; 

    if (sendFile.value != "") { 
     sendFile.remove_class("alert-danger"); 
     var data = serv + "?fileName=" + sendFile.value; 
     Message.post(data, Message.cb_sendFile); 
    } else { 
     sendFile.add_class("alert-danger"); 
    } 
} 

Message.cb_sendFile = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     var resp = JSON.parse(this.responseText); 
     var el = document.getElementsByClassName("upload-info")[0]; 
     if (resp.status == "ok") { 
      el.innerHTML = "<button type=\"button\" class=\"btn btn-success glyphicon glyphicon-ok\"> Success</button>"; 
     } else { 
      el.innerHTML = "<button type=\"button\" class=\"btn btn-danger glyphicon glyphicon-remove\"> Failure</button>"; 
     } 
    } 
} 

Message.displayInputFile = function (src) { 
    var file = src.value; 
    var fileInput = document.getElementsByClassName("doc-input")[0]; 
    fileInput.remove_class("alert-danger"); 
    fileInput.value = file.replace("C:\\fakepath\\", ""); 
} 

Message.getStatus = function() { 
    console.log("do nothing"); 
} 

window.onload = setTimeout(Message.start, 1); 

가 index.html을 수 있습니다 :

<!DOCTYPE html> 
<html lang="en"> 
    <head> 
     <meta charset="utf-8"></meta> 
     <title>aboudabi</title> 
     <link rel="stylesheet" href="./css/bootstrap.min.css"></link> 
     <link rel="stylesheet" href="./css/main.css"></link> 
    </head> 

    <body> 
     <nav class="navbar navbar-default navbar-fixed-top"> 
      <div class="container"> 
       <div class="navbar-header"> 
        <a class="navbar-brand" href="#">aboudabi</a> 
       </div> 

       <div class="login-registration-input"> 
        <ul class="nav navbar-nav navbar-right navbar-user-status"> 
        </ul> 
       </div> 
      </div> 
     </nav> 

     <div class="row col-lg-12"> 
      <div class="file-input col-lg-6 col-lg-offset-1"> 
       <input class="form-control doc-input" style="width: 400px; display: inline;" placeholder="Your file..."></input> 
       <div class="file-upload btn btn-default"> 
        <span>Browse</span> 
        <input class="upload input-upload" type="file"/> 
       </div> 
       <button type="button" class="btn btn-primary glyphicon glyphicon-upload btn-send-file"> Send</button> 
       <br> 
       <div class="upload-info col-lg-6"> 
       </div> 
      </div> 

      <div class="confirm-registration col-lg-5"> 
      </div>   
     </div> 

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
     <script src="./js/bootstrap.min.js"></script> 
     <script src="./js/index.js"></script> 
    </body> 
</html> 
+5

여기에 노드 코드가 보이지 않습니다. 서버에서'require ('index.js')'와 같은 것을 사용하여'index.js'를 실행 한 것처럼 들립니다. 그렇다면,'express.static' 또는'res.sendFile' 또는 이와 비슷한 접근 방식으로 파일을 제공해야합니다. – m59

+0

감사합니다. 당신이 말할 때 나는 이해하지 못합니다 : 파일을 제공하십시오 ... – wipman

+0

당신이 알아야 할 모든 것을 설명하기 위해, 나는 다양한 주제에 대해 많은 세부 사항을 설명해야 할 것입니다. 안녕하세요 세계 노드 앱에서 작업 한 다음 익스프레스가 적용된 안녕하세요 앱을 사용하여 진행 상황을 이해하고 있는지 확인하는 것이 가장 좋습니다. – m59

답변

0

이 때문에 당신은 내가 가장 기본적인 설정을 설명하고 거기에서 각각의 예에서 복잡성의 또 다른 레이어를 추가 할 것입니다 설정 노드의 서버를하는 방법을 이해하는 데 문제가 될 것 같다.

/** Make a server that responds to all requests with index.html **/ 

var http = require('http'); 
var fs = require('fs'); // interact with file system 

http.createServer(function (req, res) { 
    // this is how the server will respond to requests 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    fs.createReadStream('index.html').pipe(res); // read the file and pipe it to the response 
}).listen(80); 


/** serve index.html for `/` or x.html for `/x` **/ 

var http = require('http'); 
var fs = require('fs'); 

http.createServer(function (req, res) { 
    var file = req.url.split('/')[1] || 'index'; // get the first word from the url 
    res.writeHead(200, {'Content-Type': 'text/html'}); 
    var readStream = fs.createReadStream(file+'.html'); 
    readStream.on('error', function(err) { 
    // file doesn't exist 
    res.writeHead(404, {'Content-Type': 'text/plain'}); 
    res.end("This page doesn't exist."); // simple text error message as response 
    }); 
    readStream.pipe(res); 
}).listen(80); 

여기서 알 수 있듯이 요청에 의미를 부여하는 코드를 작성해야합니다. 당신이 돈 때문에 '물론

if (req.url === '/js/myFile.js') { 
    var readStream = fs.createReadSteam('/js/myFile.js'); 
    // set headers, handle errors and such, then 
    readStream.pipe(res); 
} 

,이 더 일반적으로 처리 할 수있는 코드를 작성합니다 요청이 /js/myFile.js의 서버에 오는 경우, 어떤 방법으로, 서버는 다음과 같이 생각한다 같은 코드를 반복해서 반복하고, 물론 누군가가 이미 필요한 코드만을 작성했습니다. Express에는 라우터와 정적 파일 서버가 내장되어있어 위 프로세스를 훨씬 더 멋지게 만듭니다.

var express = require('express'); 
var app = express(); 

// serve all files in `js` folder 
app.use(express.static('/js')); 

// respond with `index.html` for all other requests 
app.get('*', function(req, res) { 
    res.sendfile('index.html'); 
}); 

app.listen(80); 
관련 문제