Search code examples
node.jsajaxgetxmlhttprequest

Ajax get request in vanilla js


I am trying to send data from the server to a webpage.But when I logged the data into the console, 'null' is printed out.

My ejs file code(home.ejs):

    <div class="body">
      <button id="get" onclick="getData()">Get data</button>
    </div>
   <script>
    function getData(){
        const xhr=new XMLHttpRequest();
        xhr.open('GET','/num');
        xhr.responseType='json';
        xhr.onload=()=>{
            const data=xhr.response;
            console.log(data);
        }
        xhr.send();
    }
   </script>

My NodeJs server code:

    app.get('/',(req,res)=>{
     res.render('home');
    })
    app.get('/num',(req,res)=>{
     res.send('success');
    })

I am sending the string 'success' as data to the webpage. I am new to AJAX requests.I know this question is very basic. It would be really helpful if someone corrects me. I need the answer only in vanilla JS.


Solution

  • Using XMLHttpRequest is kinda cumbersome. I would suggest you to use the fetch function like this:

    fetch('/num')
        .then((response) => response.text())
        .then((text) => console.log(text));
    

    Because you are sending a plain string back to the client, you need to use the text method of the response object.