How to send data to node js server with ajax - node.js

I'm trying to read data sent to node.js server.
Client side:
const sendToDB =(date)=> {
var xhttp = new XMLHttpRequest();
var d = JSON.stringify(date);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(d);
}
};
xhttp.open("POST", "api/info", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(d);
}
and the server:
var http = require('http');
var server = http.createServer(function(req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
req.on('data', function (chunk) {
console.log(req.body.date);
});
res.end();
});
server.listen(3001);
how to receive data sent with xhttp.send(d) in node js server ?

var server = http.createServer(function(req, res) {
if(req.method == "POST"){
var clientData = '';
req.on('data', function (chunk) {
clientData+=chunk;
});
req.on('end',function(){
console.log(JSON.parse(clientData));
})
}
res.end();
});

you should use the header "Content-Type", "application/json" as you send some json data.
make sure you send a such an object :
{
date: {
foo: bar
}
}
as your server is expecting it in the body req.body.date

Related

using Node.js to make request, Yelp API error

I am writing my Node.js file now, which is to send requests to Yelp API and get the JSON response for client. I test my code in localhost.
I have seen the requesting url and both format and data are correct.
However, I get an error message when requesting this API:
connect ECONNREFUSED 127.0.0.1:443
Here is my Node.js code:
http.createServer(function (req, res) {
// data from the client
var some_data;
// send a GET request to Yelp’s API
var https = require('https');
var yelpMatch_url = encodeURI("https://api.yelp.com/v3/businesses/matches/best?some_data;
var headers = {
'Authorization': 'Bearer myAPI_KEY'
};
https.get({url: yelpMatch_url, headers: headers}, function(response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
// write response json
res.write(body);
res.end();
});
}).on('error', function(e) {
console.log(e.message);
});
}).listen(myPort);
Why this error ?
It looks you are doing the request to https on your localhost.
Make sure your server is running locally, and update the get method as follows:
https.get(yelpMatch_url, {headers: headers}, function(req, response) {
var body = '';
response.on('data', function (chunk) {
body += chunk;
});
response.on('end', function () {
// write response json
res.write(body);
res.end();
});
}).on('error', function(e) {
console.log(e.message);
});
Thanks! I figured it out. The format should be like this:
var https = require('https');
var myurl = "http://www.example.com";
var options = {
url: myurl,
headers: {
'Authorization': 'Bearer myKeyID'
}
};
https.get(options, function(response) {
... }

Chaining GET request with a response Node.js

I am trying to perform a GET request to an API and return the data from the API response to the client. I think the client receives a response before the GET request to the API finishes. How can I change the code to ensure that the response from the API is passed on to the client?
if (request.method == 'POST' && request.url == '/locationdata') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var formattedLocation = body.replace(/[\[\]']+/g, '');
var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation;
response.writeHead(200, { 'Content-Type': 'application/json' });
var apiData = '';
var apirequest = function () {
https.get(urlAPI, function (response) {
response.on('data', function (data) {
apiData += data;
});
response.on('end', function () {
console.log(apiData);
return apiData;
});
});
}
response.end(apirequest);
});
return;
}
You are ending the response to the client before you get all the data from the api. Moving the response.end() call up to the end of the api response should fix it:
if (request.method == 'POST' && request.url == '/locationdata') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var formattedLocation = body.replace(/[\[\]']+/g, '');
var urlAPI = 'https://api.darksky.net/forecast/166731d8eab28d33a26c5a51023eff4c/' + formattedLocation;
response.writeHead(200, { 'Content-Type': 'application/json' });
var apiData = '';
https.get(urlAPI, function (apiResponse) {
apiResponse.on('data', function (data) {
apiData += data;
});
apiResponse.on('end', function () {
console.log(apiData);
// send response to browser after we get all the data from the api
response.end(apiData);
});
});
// remove this because we moved it up
//response.end(apirequest);
});
return;
}

NodeJS data throughput

I've set up a NodeJS server which can be accessed by a client. Every once in a while it's necessary to let the server connect to a second server and feed the information retrieved back to the client.
Connecting to the second server is the easy part, but to be honest I have no idea how to send it back to the client. res.write seems to be forbidden during the connection with the second server.
The connection from the client is handled by handleGetRequest. The connection with the second server starts at http.get.
var http = require('http');
var url = require('url');
var server = http.createServer(function(req, res) {
var url_parsed = url.parse(req.url, true);
if (req.method ==='GET') {
handleGetRequest(res, url_parsed);
} else {
res.end('Method not supported');
}
});
handleGetRequest = function(res, url_parsed) {
if (url_parsed.path == '/secondary') {
var OPTIONS = {
hostname: "localhost",
port: "8900",
path: "/from_primary"
}
http.get(OPTIONS, function(secget) {
resget.on('data', function(chunk) {
// either store 'chunk' for later use or send directly
});
}).on('error', function(e) {
console.log("Error " + e.message);
});
} else {
res.writeHead(404);
}
res.end('Closed');
};
server.listen(8000);
How do I send the chunk from http.request to the client?
I thinks passing the callback to the handleGetRequest will fix this issue:
if (req.method === 'GET') {
handleGetRequest(url_parsed, function (err, response) {
if (err) {
return res.sendStatus(500);
}
res.json(response);
});
} else {
res.end('Method not supported');
}
handleGetRequest = function (url_parsed, callback) {
// OPTIONS ...
http.get(OPTIONS, function(resget) {
var data = '';
resget.on('data', function(chunk) {
data += chunk;
});
resget.on('end', function() {
callback(null, data);
});
}).on('error', function(e) {
callback(e);
});
}
Thanks to #TalgatMedetbekov for the suggestions. I managed to implement it like this:
var http = require('http');
var url = require('url');
var server = http.createServer(function(req, res) {
var url_parsed = url.parse(req.url, true);
if (req.method ==='GET') {
handleGetRequest(res, url_parsed);
} else {
res.end('Method not supported');
}
});
handleGetSecondaryRequest = function(callback, res) {
var OPTIONS = {
hostname: "localhost",
port: "8900",
path: "/from_primary"
}
var data = null;
http.get(OPTIONS, function(func, data) {
func.on('data', function(chunk) {
data += chunk;
});
func.on('end', function() {
callback(res, data);
});
}).on('error', function(e) {
callback(res, e);
})
};
var secReqCallback = function(res, recData)
{
res.write(recData);
res.end("END");
};
handleGetRequest = function(res, url_parsed) {
if (url_parsed.path == '/secondary') {
handleGetSecondaryRequest(secReqCallback, res);
} else {
res.writeHead(404);
}
};
server.listen(8000);
It works, kind of. There's an 'undefined' in front of the string which I can't find the cause for, but the basic functionality works perfect.
The callback construction is necessary to synchronize the asynchronous nature of NodeJS.

Blocking requests coming from host A to host B nodejs

My nodejs httpserver (i'm not using express) is hosted in HOST A, domain: www.host-a.com and does this:
dispatcher.addListener("post", "/admin/insert_data", function(req, res) {
var body='';
req.on('data', function(chunk) {
body += chunk.toString();
});
req.on('end', function() {
var parsedbody = require('querystring').parse(body);
MongoClient.connect('mongodb://localhost:27017/database1', function(err, db) {
if (err) {
res.writeHead(500) ;
return res.end('Database offline') ;
}
console.log("Connected correctly to server");
var col = db.collection('mycollection');
col.insert(parsedbody, function() {
db.close();
var json = JSON.stringify({status: "0"});
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(json);
});
});
});
});
The client side is the following:
$("form[name='manage_notizie']").submit(function(e) {
req="../admin/insert_data"
var tmp_notizia = $( "input[name=notizia]" ).val();
var tmp_id_notizia = $( "input[name=id_notizia]" ).val();
$.ajax({
url: req,
type: "POST",
data: {id_notizia:tmp_id_notizia, notizia:tmp_notizia},
async: false,
success: function (msg) {
location.reload();
},
error: function (msg) {
alert("Errore nel server")
},
cache: false,
});
e.preventDefault();
});
I know that by deafult, if I don't specify any access control allow origin, the server will respond only if the request arrives from itself (host a).
Now, for example if a request comes from www.host-b.com to www.host-a.com/insert_data, my server would not answer to the request (like I want) but it does the computing stuffs (which I don't want)
Am I missing something?

How can I know if the request has body?

I have this code I wrote for my server:
var http = require("http");
var url = require("url");
var routing = require("./RoutingPath");
var email = require('./NewServices.js');
var config = require ('./config.js');
function start() {
function onRequest(request, response) {
var path = url.parse(request.url).pathname;
var params = url.parse(request.url,true).query;
if (request.url === '/favicon.ico')
{
}
else
{
var data;
request.on('data', function(chunk) {
console.log("Received body data:");
console.log(chunk.toString());
data = chunk.toString();
});
routing.Route(path.toLowerCase(), params, data ,function(recordset){
response.writeHead(200, {"Content-Type": "application/json"});
if (recordset != null)
{
if (recordset.respondMessage == "GeneralSqlError")
{
var msg = JSON.stringify(recordset, null, 4);
console.log(msg);
email.SendEmailErrorNotify(msg, function(err){
if(err)
console.log(err);
});
}
else
{
console.log(JSON.stringify(recordset, null, 4));
}
response.write(JSON.stringify(recordset, null, 4));
}
response.end();
console.log();
});
}
}
http.createServer(onRequest).listen(8888);
console.log("Server has started!");
}
Sometimes the post request has data inbody. When there's a body I need to use it and process data.
The variable "data" in the following line should have data when it called:
routing.Route(path.toLowerCase(), params, data ,function(recordset){
...
How can I know if I have body?

Resources