Answer the question
In order to leave comments, you need to log in
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();
});
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);
}
}
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();
});
Answer the question
In order to leave comments, you need to log in
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')});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question