U
U
Umid2017-01-19 22:58:42
Node.js
Umid, 2017-01-19 22:58:42

How to get data from a get request from a client (Ajax), on the server?

Server script:

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


var server = http.createServer(function(req, res) {
  switch(req.url) {
    case '/':
      fs.readFile('index.html', function(err, content) {
        if(err) {
          res.status = 500;
          res.end('server error');
        } else {
          res.writeHead('Content-type', 'text/html; charset=utf-8');
          res.end(content);
        }
      });
      break;
    default: 
      res.end('Error');
  }
}).listen('1333');

server.on('request', function(req, res) {
  res.writeHead(200);
  console.log(req.method);
  console.log(req.headers);
  console.log(req.url);
  res.write('hi');
  res.end();
});

Client script:
var button = document.getElementById('button');
button.onclick = function() {
  var text = document.getElementById('text').value;


  var xhr = new XMLHttpRequest();
  xhr.open('GET', 'info.json', false);
  xhr.send();

  if(xhr.status != 200) {
    alert(xhr.status + ': ' + xhr.statusText);
  } else {
    alert(xhr.responseText);
  }
}

How to get the values ​​on the server that I sent from the client?
What event to track?
Tried via:
server.on('request', function(req, res) {
  res.writeHead(200);
  console.log(req.method);
  console.log(req.headers);
  console.log(req.url);
  res.write('hi');
  res.end();
});

So now he doesn't want to give me index.html either.
When starting the server, the first time you enter the site, it gives "hi".
And the second time (when reloading the page) the server is already falling.
48df27d4fa2e4a7a9b2cb28197a96707.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Y
Yaroslav, 2017-01-21
@DarCKoder

According to the correspondence.
The code I am giving is not intended to be used! This is just an example of native ajax and async from nodejs. In general, you need to adhere to at least the rest, and if something flies to the server, then it must be from the form and post / put request. Get is only for getting data from the server.
And requests in the node are not processed in this way.
And the response, if the Cyrillic alphabet has arrived, will send back the work.
Everything that is written below is purely for understanding the essence.

var simplePage = '<h1>тестовая отправка данных без формы</h1>'+
'<hr><input type="text" id="txt">'+
'<input type="button" id="button" value="отправить что-то">'+
'<script>(function(){'+
'var button = document.getElementById("button");'+
'button.onclick = function(){var xhr = new XMLHttpRequest();'+
'xhr.open("GET","/toserver/"+document.getElementById("txt").value, true);xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");'+
'xhr.send();'+
'xhr.onreadystatechange = function(){if(xhr.readyState == 4) alert(xhr.responseText)}}'+
'})()</script>';
var http = require('http');
var server = http.createServer(function(req,res){
  console.log(req.url);
  if (req.url === '/') {
    res.writeHead(200, {'Content-type' : 'text/html; charset=utf-8'});
    res.write(simplePage);
    res.end();
  }
  else{
    res.writeHead(200, {'Content-type' : 'text/html; charset=utf-8'});
    //res.write(simplePage);
    res.end('вы отправили нам '+req.url.slice(10));
  }
});	
server.listen(1333,function(){console.log('listen server at 1333')});

M
Michael, 2017-01-19
@mak_ufo

server.on('request', (req, res) => {})

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question