POST data from a client javascript page to a node server - javascript

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
}
});

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.

How to fix not getting text response from Post request

I'm new to using nodejs and javascript so I'm sorry if I'm just doing something obviously wrong. I have a nodejs app I'm running and serves a html page. That html page can send Post requests using XMLHttpRequest. The request goes though and my node app calls the function that my request is meant to invoke. The problem is I want to get some data back from that request so I am trying to get that from the response to the request. The issue is I am getting an empty response and I do not know why.
Here is my request.
function SendCachedTriangulation(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('responseLog').textContent = "sent triangulation: " + this.response;
}
};
xhttp.open("Post", "/sendCachedTriangulation");
xhttp.setRequestHeader("Content-type", "application/json");
var text = '{ "data" : ' + '{ "someData":"' + '1' + '" } }';
xhttp.send(text);
return false;
}
The result I get from this is response is empty. It does update the element I am trying to update but it just says "sent triangulation: ".
On the nodejs side this is my code.
router.post('/sendCachedTriangulation', (req, res, next) => {
client.SendCachedTriangulation(() => {
res.status(200)
;}, req.body
);
res.status(200).message = "sent triangulation";
res.send();
});
Which this seems to be calling my function to send cached triangulation properly i just don't get that "sent triangulation" message.
What do I need to change to display that message in my HTML page?
Actually I understood your snippet. I also understand that is complicated at first time with Node, because is everything Javascript. Let me explain: in your HTML, think the request is OK, but actually have, let's say, two files: HTML file, that performs the request, and the node HTTP server, that responds the request. So I mean something like:
// /server/app.js
router.post('/sendCachedTriagulation', (req, res, next) => {
res.status(200).send("sent triangulation")
})
// /client/index.html
client.SendCachedTriangulation(/* do stuff */)

How to handle JSON data from XMLHttpRequest POST, using nodeJS

Overarching goal is to save some JSON data I create on a webpage to my files locally. I am definitely sending something to the server, but not in format I seem to able to access.
JsonData looks like:
{MetaData: {Stock: "UTX", Analysis: "LinearTrend2"}
Projections: [2018-10-12: 127.62, 2018-10-11: 126.36000000000001, 2018-10-10: 132.17, 2018-10-09: 140.12, 2018-10-08: 137.73000000000002, …]}
XMLHttpRequest on my webpage:
function UpdateBackTestJSON(JsonUpdate){ //JsonUpdate being the JSON object from above
var request = new XMLHttpRequest();
request.open('POST', 'UpdateBackTestJSON');
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
// request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
request.onload = function() {
console.log("Updated JSON File");
};
console.log("about to send request");
console.log(JsonUpdate);
request.send(JSON.stringify(JsonUpdate));
}
and I handle posts on my server (rather carelessly I realize, just going for functionality as a start here)
var http = require('http')
, fs = require('fs')
, url = require('url')
, port = 8008;
var server = http.createServer (function (req, res) {
var uri = url.parse(req.url)
var qs = require('querystring');
if (req.method == 'POST'){
var body = '';
req.on('data', function (data){
body += data;
// 1e6 === 1 * Math.pow(10, 6) === 1 * 1000000 ~~~ 1MB
if (body.length > 1e6){
// FLOOD ATTACK OR FAULTY CLIENT, NUKE REQUEST
req.connection.destroy();
}
});
req.on('end', function () {
var POST = qs.parse(body);
console.log(POST); // PARSED POST IS NOT THE RIGHT FORMAT... or something, idk whats going on
UpdateBackTestData(POST);
});
}
function UpdateBackTestData(TheJsonData){
console.log("UpdateBackTestData");
console.log(TheJsonData);
JsonUpdate = JSON.parse(TheJsonData);
console.log(JsonUpdate["MetaData"]);
//var Stock = JsonUpdate["MetaData"]["Stock"];
// var Analysis = JsonUpdate["MetaData"]["Analysis"];
fs.writeFile("/public/BackTestData/"+Analysis+"/"+Stock+".json", TheJsonData, function(err){
if(err){
console.log(err);
}
console.log("updated BackTest JSON!!!");
});
}
Most confusing to me is that when I run this, the Json object Im am trying to pass, does go through to the server, but the entirety of the data is a string used as a key for a blank value in an object. when I parse the body of the POST, I get: {'{MetaData:{'Stock':'UTX','Analysis:'LinearTrend2'},'Projections':[...]}': ''}. So my data is there... but not in a practical format.
I would prefer not to use express or other server tools, as I have a fair amount of other services set up in my server that I don't want to go back and change if I can avoid it.
Thanks for any help

POST Ajax calls with Node, express & vanilla JS

I am trying to do some ajax calls with vanilla JS.
In the back-end I am working with node in the express-framework.
It seems that the data I want to send never actually reaches my back-end. Has anyone an idea what is going on?
My Javascript:
<form id='ajax_form' method='POST' action='/admin/new/tag'>
<input type='text' name='tag' id="tag">
<button type='submit'>Create new tag</button>
</form>
<script>
var ajaxForm = document.querySelector("#ajax_form").addEventListener("submit", function(e){
e.preventDefault();
var form = e.target;
var data = new FormData(form);
var request = new XMLHttpRequest();
request.onreadystatechange = function(){
if(request.response){
[...]
}
}
request.open(form.method, form.action)
request.send(data);
});
</script>
When I iterate over the data object, everything seems to be as it should, returning the keys and values I want to submit through the form.
This is my back-end set-up:
var express = require("express"),
app = express(),
mysql = require("mysql"),
bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({extended: true}));
app.post('/admin/new/tag', function(req, res){
var tag = {tag_name: req.body.tag};
var q = 'INSERT INTO tags SET ?';
connection.query(q, tag, function(error, results, fields){
if (error) throw error;
res.send('succeed');
});
});
When I console.log(req.body.tag), I just get Undefined and req.body is just an empty object.
My database also throws an error as the key tag_name should not be NULL.
When I look at the network panel I receive 503 service unavailable.
Thank you for your response and input!
On server-side you muse use multer for handling multipart/form-data.
Alternatively, you can send the data in JSON format to the server like this way:
var xhr = new XMLHttpRequest();
var data = {
param1: 'value1',
param2: 'value2'
};
xhr.open('POST', '/query');
xhr.onload = function(data) {
console.log('loaded', this.responseText);
};
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify(data));
Server-side set the bodyParser to JSON
app.use( bodyParser.json() );
And now you should be able to read the values ​​through the req.body.. syntax.

Client side can not take the json data

I have a nodejs server and the code that I have as below. I send an AJAX request and I want the server to send me a response of a json data. When I put res.write()("string data like hello hello") in the server code, client side can take the value of inside and I can see the value on the console. But I cannot get json value with this function. I tried res.end() and res.send() functions as well but it didn't work. How can I send the json value and the following client side code can take the value correctly?
Server side,
app.use('/', function(req, res) {
console.log("req body app use", req.body);
var str= req.path;
if(str.localeCompare(controlPathDatabaseLoad) == 0)
{
console.log("controlPathDatabaseLoad");
mongoDbHandleLoad(req, res);
res.writeHead('Content-Type', 'application/json');
res.write("Everything all right with database loading"); //I can get this message
//res.end(json) I can not get json message with this function as well
res.send("OK");
//res.send(JSON.stringify(responseBody)); I can not get json message
}
Client side,
function loadDatabaseData()
{
console.log("loadDatabaseData");
var oReq = new XMLHttpRequest();
oReq.open("GET", "http://192.168.80.143:2800/load", true);
oReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
oReq.onreadystatechange = function() {//Call a function when the state changes.
if(oReq.readyState == 4 && oReq.status == 200) {
console.log("http response", oReq.response);
console.log("http responseText", oReq.responseText);
}
}
oReq.send();
}

Categories

Resources