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.
Related
I'm trying to learn XMLHttpRequests. I'm trying to send some input to the server, but when it gets there, the Object is empty, like {}
That setRequestHeader I commented out, if it's in, the object gets printed out properly, but I get an error that it should be open on the browser. BUT if I put it after the open() statement, it stops working again and the object arrives empty. I also have tried all of that and also JSON.stringfy the variable before sending it but it also didn't work.
//server.js
const express = require('express');
const app = express();
const cors =require('cors')
app.use(cors())
app.use(express.urlencoded({extended:true}))
app.post('/frases', function(req, res) {
console.log(req.body);
const frase = new phrase(req.body);
// console.log(frase);
})
app.listen(3000, () => console.log('listening on 3000...'));
//script.js
var form = document.getElementsByTagName('form')[0];
const xhr = new XMLHttpRequest();
// xhr.setRequestHeader('Content-Type', 'application/json');
form.onsubmit = (e) => {
e.preventDefault();
const thisName = form.elements[0].name;
const thisValue = form.elements[0].value;
const frase = {[thisName]:thisValue};
console.log(frase)
xhr.open('POST', 'http://localhost:3000/frases');
xhr.send(frase);
};
<!-- index.html -->
<form action = "http://localhost:3000/frases" method="post">
<label for="frasefavorita"> Qual é a sua frase favorita?
<input id= 'frase' type="text" name="frasefavorita">
<button id= 'send-frase' type="submit">Enviar</button>
</form>
req.body is empty by default because the body of the incoming request is not read by default. You need middleware that matches the incoming content-type in order to read that body, parse it and put the results into req.body.
And, in your xhr call, you have to decide what content-type you're going to use to send the data, have to put the data into that content-type and you have to set that header appropriately. Then, you will be able to add the right middleware to your server to read and parse that body and then, and only then, can you access it in req.body on your server.
If you were going to send it as JSON, then you can do this on the client to set the content-type for JSON and to format the data as JSON:
form.onsubmit = (e) => {
e.preventDefault();
const thisName = form.elements[0].name;
const thisValue = form.elements[0].value;
const frase = {[thisName]:thisValue};
const xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-Type", "application/json");
xhr.open('POST', 'http://localhost:3000/frases');
xhr.send(JSON.stringify(frase));
};
Then, on your server, you can add this middleware before your /frases route handler:
// read and parse incoming JSON request bodies
app.use(express.json());
That will read and parse the application/json content-type data coming from your Ajax call.
P.S. I would suggest you use the fetch() interface for writing new code, not the XMLHttpRequest API. fetch() is just much easier to use and a more modern design (using promises).
Try to set the header after you call the open function
xhr.open('POST', 'http://localhost:3000/frases');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(frase);
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.
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
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
}
});
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));