IT Share you

node.js로 기본 Ajax 보내기 / 받기

shareyou 2021. 1. 7. 19:57
반응형

node.js로 기본 Ajax 보내기 / 받기


그래서 나는 문자열에 대한 요청을 받아 배열에서 무작위로 하나를 선택하고 선택된 문자열을 반환하는 매우 기본적인 node.js 서버를 만들려고합니다. 불행히도 몇 가지 문제가 있습니다.

다음은 프런트 엔드입니다.

function newGame()
{
   guessCnt=0;
   guess="";
   server();
   displayHash();
   displayGuessStr();
   displayGuessCnt();
}

function server()
{
   xmlhttp = new XMLHttpRequest();

   xmlhttp.open("GET","server.js", true);
   xmlhttp.send();

   string=xmlhttp.responseText;
}

요청을 server.js로 보내야합니다.

var http = require('http');

var choices=["hello world", "goodbye world"];

console.log("server initialized");

http.createServer(function(request, response)
{
    console.log("request recieved");
    var string = choices[Math.floor(Math.random()*choices.length)];
    console.log("string '" + string + "' chosen");
    response.on(string);
    console.log("string sent");
}).listen(8001);

여기에는 몇 가지 잘못된 점이 있습니다.

  1. 이 두 파일을 "연결"하는 xmlhttp.open방식 메서드와 response.on문자열을 프런트 엔드로 다시 보내는 데 사용하는 모두 올바르지 않은 느낌을받습니다 .

  2. localhost에서이 페이지를 호출하는 방법과 약간 혼란 스럽습니다. 프론트 엔드의 이름은 index.html이고 서버는 8001에 게시됩니다. server.js를 초기화 한 후 초기 html 페이지에 액세스하려면 localhost에서 어떤 주소로 이동해야합니까? .listen(index.html)또는 그와 비슷한 것으로 변경해야합니까 ?

  3. 이것을 구현하는 방법에 다른 명백한 문제가 있습니까 ( .responsetext사용 )

(긴 다중 질문 게시물에 대해 죄송하지만 다양한 자습서와 node.js 소스는 모두 사용자가 이미 이러한 사항을 이해하고 있다고 가정합니다.)


  1. 요청은 인스턴스화하는 server.js 파일이 아니라 서버에 대한 것이어야합니다. 따라서 요청은 다음과 같아야합니다. xmlhttp.open("GET","http://localhost:8001/", true);또한 프런트 엔드 (index.html)를 제공하고 동일한 URI에서 AJAX 요청을 제공하려고합니다. 이를 수행하려면 AJAX 요청과 일반 http 액세스 요청을 구분하는 논리를 server.js에 도입해야합니다. 이렇게하려면 GET / POST 데이터 (예 : call http://localhost:8001/?getstring=true)를 도입하거나 AJAX 요청에 대해 다른 경로를 사용합니다 (예 : call http://localhost:8001/getstring). 그러면 서버 측에서 요청 객체를 검사하여 응답에 쓸 내용을 결정해야합니다. 후자의 경우 요청을 구문 분석하려면 'url'모듈을 사용해야합니다.

  2. 전화를 올바르게하고 listen()있지만 응답을 잘못 작성했습니다. 를 탐색 할 때 우선, 당신이 원하는 경우 index.html을 봉사 에 http : // localhost를 : 8001 / , 다음을 사용하여 응답 파일의 내용을 작성해야 response.write()하거나 response.end(). 먼저 fs=require('fs')파일 시스템에 대한 액세스 권한을 얻으려면 포함해야합니다 . 그런 다음 실제로 파일을 제공해야합니다.

  3. XMLHttpRequest를 비동기 적으로 사용하고 (세 번째 매개 변수 = true, 수행 한대로) 응답으로 무언가를 수행하려면 지정된 콜백 함수가 필요합니다. AJAX 요청이 완료되기 전에 해당 행이 실행되기 때문에 (즉, responseText가 여전히 비어 있기 때문에) 지금 가지고있는 방식 stringundefined(또는 아마도 null) 일 것입니다. 동기식으로 사용하는 경우 (세 번째 매개 변수 = false) 수행 한대로 인라인 코드를 작성할 수 있습니다. 요청하는 동안 브라우저를 잠그므로 권장하지 않습니다. 비동기 작업은 일반적으로 완료되면 응답을 처리 할 수있는 onreadystatechange 함수와 함께 사용됩니다. XMLHttpRequest의 기초를 배워야합니다. 여기서 시작 하십시오 .

다음은 위의 모든 사항을 통합하는 간단한 구현입니다.

server.js :

var http = require('http'),
      fs = require('fs'),
     url = require('url'),
 choices = ["hello world", "goodbye world"];

http.createServer(function(request, response){
    var path = url.parse(request.url).pathname;
    if(path=="/getstring"){
        console.log("request recieved");
        var string = choices[Math.floor(Math.random()*choices.length)];
        console.log("string '" + string + "' chosen");
        response.writeHead(200, {"Content-Type": "text/plain"});
        response.end(string);
        console.log("string sent");
    }else{
        fs.readFile('./index.html', function(err, file) {  
            if(err) {  
                // write an error response or nothing here  
                return;  
            }  
            response.writeHead(200, { 'Content-Type': 'text/html' });  
            response.end(file, "utf-8");  
        });
    }
}).listen(8001);
console.log("server initialized");

프런트 엔드 (index.html의 일부) :

function newGame()
{
   guessCnt=0;
   guess="";
   server();
   displayHash();
   displayGuessStr();
   displayGuessCnt();
}

function server()
{
   xmlhttp = new XMLHttpRequest();
   xmlhttp.open("GET","http://localhost:8001/getstring", true);
   xmlhttp.onreadystatechange=function(){
         if (xmlhttp.readyState==4 && xmlhttp.status==200){
           string=xmlhttp.responseText;
         }
   }
   xmlhttp.send();
}

You will need to be comfortable with AJAX. Use the mozilla learning center to learn about XMLHttpRequest. After you can use the basic XHR object, you will most likely want to use a good AJAX library instead of manually writing cross-browser AJAX requests (for example, in IE you'll need to use an ActiveXObject instead of XHR). The AJAX in jQuery is excellent, but if you don't need everything else jQuery offers, find a good AJAX library here: http://microjs.com/. You will also need to get comfy with the node.js docs, found here. Search http://google.com for some good node.js server and static file server tutorials. http://nodetuts.com is a good place to start.

UPDATE: I have changed response.sendHeader() to the new response.writeHead() in the code above !!!


Express makes this kind of stuff really intuitive. The syntax looks like below :

var app = require('express').createServer();
app.get("/string", function(req, res) {
    var strings = ["rad", "bla", "ska"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
})
app.listen(8001)

http://expressjs.com/guide.html

If you're using jQuery on the client side you can do something like this:

$.get("/string", function(string) {
    alert(string)
})

I was facing following error with code (nodejs 0.10.13), provided by ampersand:

origin is not allowed by access-control-allow-origin

Issue was resolved changing

response.writeHead(200, {"Content-Type": "text/plain"});

to

response.writeHead(200, {
                 'Content-Type': 'text/html',
                 'Access-Control-Allow-Origin' : '*'});

Here is a fully functional example of what you are trying to accomplish. I created the example inside of hyperdev rather than jsFiddle so that you could see the server-side and client-side code.

View Code: https://hyperdev.com/#!/project/destiny-authorization

View Working Application: https://destiny-authorization.hyperdev.space/

This code creates a handler for a get request that returns a random string:

app.get("/string", function(req, res) {
    var strings = ["string1", "string2", "string3"]
    var n = Math.floor(Math.random() * strings.length)
    res.send(strings[n])
});

This jQuery code then makes the ajax request and receives the random string from the server.

$.get("/string", function(string) {
  $('#txtString').val(string);
});

Note that this example is based on code from Jamund Ferguson's answer so if you find this useful be sure to upvote him as well. I just thought this example would help you to see how everything fits together.

ReferenceURL : https://stackoverflow.com/questions/6011984/basic-ajax-send-receive-with-node-js

반응형