how to send json data from html page to node.js server - javascript

i want to send some json data from my client page to server page of node.js,
here i have my server page :
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.post('/', function(req,res){
res.send('recieved request');
console.log(req.body);
});
app.listen(8081);
console.log('listening on 8081');
client page:
var name ='someName';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function(){
if(this.readyState== 4 && this.status == 200){
console.log(this.responseText);
}
};
xhttp.setRequestHeader({'Content-Type': 'application/json'});
xhttp.open('POST', 'http://localhost:8081', true);
xhttp.send(JSON.stringify({'name' : name}));
I got the result as a null json {}.
NOTE: I don't want to about submission of a form , i just want to send JSON data from html file to node.js file.

The correct signature for a call to XMLHTTPRequest#setRequestHeader is setRequestHeader(header, value);
Change
xhttp.setRequestHeader({'Content-Type': 'application/json'});
to
xhttp.setRequestHeader('Content-Type', 'application/json');
Docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader

Related

Extracting of HTTP Post in Node Express doesn't work

I just want to extract an http-Post but I didn't get it working. Can somebody help me please? The request is made by my HTML Frontend using XMLHttpRequest() and the backend is node.js. When I send the request I only get an empty Object {}
Node Backend
var express = require('express');
const bodyParser = require('body-parser');
var app = express();
app.use(express.json());
app.post('/save_options', (req, res) => {
console.log(req.body);
res.sendStatus(200);
});
Frontend
let DATA_FRONTEND_OPTIONS = {
"test":"1"
}
function save_options_to_database() {
var do_it_async = true;
var request = new XMLHttpRequest();
request.onload = function () {
var status = request.status;
var data = request.responseText;
}
request.open("POST", "/save_options", do_it_async);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
//request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.send(JSON.stringify(DATA_FRONTEND_OPTIONS));
}
Simply add
app.use(express.urlencoded());
to your express configuration.
Here is great explanation:
https://stackoverflow.com/a/51844327/8522881
You have to add express.json() and express.urlencoded() for POST request.
Example:
app.use(express.json());
app.use(express.urlencoded());
Because in POST request the data which is sending is in form of some type of data object and you have to tell the server to accept or store that type of data (object), which is enclosed in the body of your POST request.
Above the same solution applied for PUT requests also.

res.send is not a function

I am making an api call and recieving the data, however, I am having trouble sending the data back to my js file. I tried using res.send but I am getting an error. I can't seem to figure out how to send the information back to the javascript file. (I took my key out of the request link. For security reasons, however, I am getting the data back from the api call). The only problem I am having is returning the data to the frontend javascript file.
This is the Javascript file that sends the original request:
/ ********** options button function makes api call to get selected cities forecast *****************
function getCityForecast(e){
var id = document.getElementById('cities');
var getValue = id.options[id.selectedIndex].value;
var suffix = getValue + ".json";
var newObj = JSON.stringify({link : suffix});
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/", true);
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(newObj);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
console.log(xhr.response);
console.log('recieved');
} else {
console.log('error');
}
}
}
My server.js file looks like this:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var path = require('path');
var request = require('request');
// ****************** Middle Ware *******************
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(express.static(__dirname + '/public'));
var retrievedString;
// **************** Post Request *******************
app.post('/', function(req, res){
var link = "http://api.wunderground.com/api/key/forecast";
retrievedString = link.concat(req.body.link);
request = http.get(retrievedString , function(res){
var body = '';
res.on('data', function(data){
body += data;
});
res.on('end', function(){
var parsed = JSON.parse(body);
console.log(parsed.forecast.txt_forecast);
res.send(parsed.forecast.txt_forecast);
});
})
.on('error', function(e) {
console.log("Got error: " + e.message);
});
});
app.listen(3000, function() { console.log('listening')});
You are overloading the definition of the variable res which is also what you called the response variable for your Express route handler method. In the callback function of the request, use a different name for that variable - for example:
request = http.get(retrievedString , function(resDoc){

How to send post request to server.js in cloud9

Hi I'm learning the mean stack on cloud9.
I've come to the point where I'm trying to send variables to my node.js server but I'm not sure if my server is picking it up. Are there any obvious errors with my post request code?
app.js(frontend angular)
console.log('begin');
var http = new XMLHttpRequest();
var params = "text=stuff";
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
console.log('onreadystatechange');
if (http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
else {
console.log('readyState=' + http.readyState + ', status: ' + http.status);
}
}
console.log('sending...')
http.send(params);
console.log('end');
this is the console response that I am getting:
begin
sending...
end
POST https://new-backup.splacorn.c9.io/myApp/server/server.js/ net::ERR_INSECURE_RESPONSE$scope.addNewUser
onreadystatechange
readyState=4, status: 0
I believe that the error that I am getting is attributed to this line:
http.open("POST", "https://new-backup.splacorn.c9.io/myApp/server/server.js/", true);
once http.send(params); calls it.
Here is the server.js file (backend)
var express = require('express');
var fs = require('fs');
var app = express();
var bodyParser = require('body-parser')
app.use(express.bodyParser());
app.post('/', function(req, res){
console.log('POST /');
res.writeHead(200);
res.end('this is from the server');
});
var port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port);
Does anyone know why I'm getting the error? Part of me thinks that I'm getting the cloud 9 server url wrong but I'm not sure... If anyone can help me figure this out that would be amazing!
I'd like to use socket.io instead.
Here's a small example of how you can do it:-
Client side code:
var io = io("http://localhost:1337");
io.emit('give me some data',{test:'testing socket.io'});
io.on('got the data',function(data){
console.log(data.test);
});
Server side code:
var app = require('express').createServer();
var io = require('socket.io')(app);
io.on('connection',function(socket){
socket.on('give me some data',function(data){
socket.emit('got the data',data);
}
app.listen(1337);
You can get socket.io here
They have both client side as well as server side code. Hope you got my point. I was at phone so couldn't type much. And also, socket.io provides real time connection between the client and the server :)

POST data from a client javascript page to a node server

Is it possible to POST data from a client javascript page to a node server (server.js) using an AJAX XMLHttpRequest()? What I am looking for is javascript code that will receive the data on the node server, specifically the values for member_nm ("newName") and member_email ("mail#google.com"). I control the server. I also understand that I can also use GET to send the text values by means of a querystring. Below is the request that is sent from the client javascript page by means of an event handler:
document.getElementById("btnAddMember").addEventListener("click", function()
{
var request = new XMLHttpRequest();
var path = "/Users/Admin/WebstormProjects/projectName/server.js";
request.onreadystatechange = function()
{
if ( request.readyState === 4 && request.status == 200 )
{
request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
request.open("POST", path, true);
request.send("member_nm=newName&member_email=mail#google.com");
}
};
});
You need to setup your server to accept this post request, the easiest will be to use Express with bodyParser middleware, like this :
var express = require('express');
var server=express();
var bodyParser= require('body-parser');
server.use(bodyParser.json());
server.post('/', function(req, res){
if(req.body){
// get the params from req.body.paramName
}
});
server.listen(8222, function(){
console.log('listening for requests ..')
});
In your client code change the 'path' to point to the server url:port, and I will put these outside of the onReadyStateChange:
request.setRequestHeader("Content-Type", "text/plain; charset=UTF-8");
request.open("POST", path, true);
request.send("member_nm=newName&member_email=mail#google.com");
This is a working solution on how to POST variables from a client javascript file to a Node server using Express. The POST is initiated on the client by means of an event handler, btnAddMember. txtName.value and txtMembershipType.value contain the values to be posted. Note the syntax that is necessary to parse the values correctly. member_nm and member_type will be used to reference the properties on the Node server. First the client javascript:
document.getElementById("btnAddMember").addEventListener("click", function()
{
var request = new XMLHttpRequest();
var path = "http://0.0.0.0:0000"; // enter your server ip and port number
request.open("POST", path, true); // true = asynchronous
request.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
var text= '{"member_nm":"' + txtName.value + '","member_type":"' + txtMembershipType.value + '"}';
request.send ( text );
});
Next is the server side code. Note that bodyParser must now be added to your project as a node_module. This can be done through the node program manager (npm). The POST statement basically parses the req.body from a JSON format to a javascript object format using a variable called 'member'. The code then logs the posted values for the two variables, member_nm and member_type. Finally a response status is sent to the client if the POST is successful.
var bodyParser = require("body-parser");
...
app.use(bodyParser.text({ type: "application/json" }));
...
// receive the POST from the client javascript file
app.post("/", function (req, res)
{
if (req.body)
{
var member = JSON.parse( req.body ); // parse req.body as an object
console.log("member_nm: " + member.member_nm );
console.log("member_type: " + member.member_type );
res.sendStatus(200); // success status
}
else
{
res.sendStatus(400); // error status
}
});

AJAX POST JSON from javascript to nodejs server

I'm trying to send a JSON object from javaScript to node.js server. I'm using a standard XMLHttpRequest to send it from javascript and a standard node.js code.
Two codes seem to be communicating normally however the node.js always gives me an empty JSON object. I'm not really sure what am I doing wrong.
This is my javascript code:
<html>
<head>
<script>
function xhrPost() {
var data = {"name":"John", "time":"2pm"};
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("POST", "http://[serverIP]:8080/addUser");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("content-type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify(data));
}
</script>
</head>
<body onload="xhrPost()">
</body>
</html>
and this is my node.js code:
var express = require("express");
var myParser = require("body-parser");
var app = express();
app.use(myParser.urlencoded({extended : true}));
app.post("/addUser", function(request, response) {
console.log(request.body); // this line allways produce {}
response.send("Message received.");
response.end();
});
app.listen(8080);
You have to use myParser.json() as a middleware. See more about it in https://github.com/expressjs/body-parser#bodyparserjsonoptions
After following line:
var myParser = require("body-parser");
You should add on more line as:
var myParser = require("body-parser");
app.use(myParser.json());// parse application/json
This was the most helpful stackoverflow page to solve my problem as well.
I was trying to get form fields, formulate them into a JSON on the client, then send to the server to use the fields for a MySQL call to a separate database.
Object {name: "", reps: "1", weight: "1", date: "", lbs: "0"}
I was able to get the object logging correctly on the client, yet every time I tried to send the data to the server,
console.log(req.body);
Would always return on the server as either
{}
undefined
Server side my setup with functioning data passing is
var express = require('express');
var mysql = require('./dbcon.js');
var app = express();
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
var request = require('request');
var myParser = require("body-parser");
var async = require('async');
app.set('view engine', 'handlebars');
app.set('port', Number(process.env.PORT || 3000));
app.use(myParser.json());
app.use(express.static('public'));
app.engine('handlebars', handlebars.engine);
On my client side js file, I have a function upon form submit that does:
var data = {
"name":document.getElementById("fname").value,
"reps":document.getElementById("freps").value,
"weight":document.getElementById("fweight").value,
"date":document.getElementById("fdate").value,
"lbs":bool
};
...
req.open("POST", "/insert", true);
req.setRequestHeader("content-type", "application/json;charset=UTF-8");
...
req.send(JSON.stringify(data));

Categories

Resources