I have an html form that has several fields which I package in a JSON, and I need to send this to a server. I have the following code on the front end:
var data = {
//data here
};
var xhr = new XMLHttpRequest();
xhr.open("POST","localhost:8000/add",true);
xhr.setRequestHeader("Content-Type","application/json");
xhr.send(data);
And then on the server, I have this code to receive it:
app.post('/add', function(req,res) {
console.log(req.body.name);
res.json(req.body.name);
});
It sends nothing; what do I need to do to get it to send the JSON?
You need to use body-parser to get values in req.body
From npm documents
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
You are not handling the response of post request,and also make sure you are using body parser at backend. So you front end code should be like this:
var data = {name:"xyz"};
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST","localhost:8000/add",true);
xhr.setRequestHeader('Content-type','application/json; charset=utf-8');
xhr.onload = function () {
var data = JSON.parse(xhr.responseText);
if (xhr.readyState == 4 && xhr.status == "201") {
console.log(data);
} else {
console.log(data);
}
}
xhr.send(json);
And your server side code should be coded like :
var express = require('express')
var bodyParser = require('body-parser')
var app = express();
// parse application/json
app.use(bodyParser.json())
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.post('/add', function(req,res) {
console.log(req.body.name);
res.status(201).json(req.body.name);
});
I tested it with this code and it success with me:
Client code same as your code.
Server Code:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/add', function(req,res) {
console.log(req.body.name);
res.json(req.body.name);
});
Related
I use vue3, vuex, express.js and mysql. In the below router get method, I call "console.log(req.body)" and shows "[object Object]", and I call "console.log(req.body.userid)" and shows "undefined".
router.get('/',async function(req,res){
const userId = req.body.userid;
console.log("req body is: "+req.body);
console.log("req.body.userid is: "+req.body.userid);
.....
}
In the below method, I pass userid value as a json object. I call "console.log("post userid: "+userinfo.userid);" and shows the the right value "1";
async getsp(){
var userinfo = JSON.parse(localStorage.getItem('user'));
console.log("post userid: "+userinfo.userid);
var userid = userinfo.userid;
var obj = {userid};
return await axios.get('//localhost:8081/getSp',obj)
.then(...)
},
And in the main router file I used body-parser, the file context is below:
require("dotenv").config();
const express = require('express');
const bodyParser = require('body-parser');
var cors = require('cors');
const signup = require('./userSignUp');
const login = require('./userLogin');
const createEvsp = require('./createEvsp');
const getSp = require('./getSp');
//const createFile = require('./createFile');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json())
app.use(cors())
app.use(express.json());
app.use(
express.urlencoded({
extended: true
})
);
app.use("/signup",signup);
app.use("/dologin",login);
app.use("/createEvsp",createEvsp);
app.use("/getSp",getSp);
//app.use("/createFile",createFile);
app.listen(8081,function () {
console.log('Server running at 8081 port');
});
The problem was an HTTP method understanding and how express works
To solve it it was needed to use the express middleware /:userid for accessing to the parameter using req.params.userid
According to the http standards for sending the data we generally use POST request.
There is a good answer in stack here Information about Get HTTP Request
Sayf-Eddine
I am trying simple api which return sml response :
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const libxmljs = require("libxmljs");
const PORT = process.env.PORT || 5000;
const app = express()
app.use(cors());
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json());
app.get('/', (req, res) => {
res.send({ "message": "success" });
});
app.get('/api', (req, res) => {
var libxmljs = require("libxmljs");
var xml = '<?xml version="1.0" encoding="UTF-8"?>' +
'<root>' +
'<child foo="bar">' +
'<grandchild baz="fizbuzz">grandchild content</grandchild>' +
'</child>' +
'<sibling>with content!</sibling>' +
'</root>';
var xmlDoc = libxmljs.parseXml(xml);
// xpath queries
var gchild = xmlDoc.get('//grandchild');
console.log(gchild.text()); // prints "grandchild content"
var children = xmlDoc.root().childNodes();
var child = children[0];
console.log(child.attr('foo').value()); // prints "bar"
res.set('Content-Type', 'text/xml');
res.send(xmlDoc);
});
app.listen(PORT, () => {
console.log(`App running on PORT ${PORT}`)
});
here everthing is showing as expected in node console, but in the APi response i am not getting XML, I am getting this error:
This page contains the following errors:
error on line 1 at column 1: Document is empty
Below is a rendering of the page up to the first error.
Please help
I see that you copy the code from github repo.
You're sending as response the xml object, not the string....
Instead of
res.send(xmlDoc);
do
res.send(xml);
I am trying to access a body from a post request sent using XMLHttpRequest to an express server. However the body of the request is empty and I cannot seem to understand why that is.
I have included a body-parser in the express app, and I have tried to replicate some code from SO answers. But I still get it wrong somehow.
<script>
const Http = new XMLHttpRequest();
Http.open('post', 'localhost:3000');
Http.send("sending something!");// this resolves to {} on the backend?
Http.onload = function() {
alert(Http.response);
};
</script>
This is how I try to handle it on my express server
const express = require("express");
let app = express()
const bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({
extended: true
}));
app.post("/post", (req, res) => {
console.log("inside of post");
console.log(req.body);
})
app.listen(3000)
This is the logs
inside of post
{}
I expect the console.log() to print "sending something!" that I try to send with the request with Http.send("sending something!");.
You have specified the body-parser to parse the body as url-encoded format which would work if you pass data like this:
Http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
Http.send("param1=value1¶m2=value2");
/* console output:
{ param1: 'value1', param2: 'value2' }
*/
In your case, the data being passed is simple string, which the backend interprets as empty JSON {} as it is unable to parse.
For it to work try setting the format of data as follows
<script>
const Http = new XMLHttpRequest();
Http.open('post', 'localhost:3000');
Http.setRequestHeader("Content-Type", "text/plain");
Http.send("sending something!");
Http.onload = function() {
alert(Http.response);
};
</script>
And in express server:
const express = require("express");
let app = express();
const bodyParser = require("body-parser");
// app.use(
// bodyParser.urlencoded({
// extended: true
// })
// );
app.use(bodyParser.text({ type: "text/plain" })); // use this instead
app.post("/post", (req, res) => {
console.log("inside of post");
console.log(req.body);
return req.body;
});
app.listen(3000);
Then you might be able to read the message "sending something!" in the backend.
Just make sure you are setting the right contentType header in XMLHttpRequest while sending and you use same type while parsing in the backend as well.
For more info on bodyParsers refer this doc
I need to send JSON to my server, but the POST requests are appearing with an empty body. Here is my typescript on the front end:
function sendData() : void {
console.log("Sending data...");
var name_ : string = (document.getElementById("name") as HTMLInputElement).value;
var id_ : string = (document.getElementById("series") as HTMLInputElement).value;
var toSend = new FormData();
toSend.append("name",name_);
toSend.append("id",id_);
var request = new XMLHttpRequest();
request.open("POST", "/add");
request.send(toSend);
}
My server has this code: I've omitted the file paths.
var Express = require('express');
var BodyParser = require('body-parser');
var Multer = require('multer');
var app = Express();
var upload = Multer();
app.use(Express.static("/public"));
app.use(BodyParser.urlencoded({extended:true}));
app.use(BodyParser.json());
app.get('/public/dataAjax.js', function(req,res){
res.sendFile("C:\\<omitted>\\dataAjax.js");
})
app.get('/', function(req,res) {
res.sendFile("C:\\<omitted>\\index.html");
});
app.post('/add', function(req,res) {
console.log("Received:");
console.log(req);
res.status(201).json(req.body.name);
});
app.listen(8000, () => console.log("Running on port 8000!"));
My problem appears to be entirely server side, as I've used flask in the past and this code worked fine. My focus here is using node with expressjs.
This only parses a request with a Content-Type of application/x-www-form-urlencoded. See docs of body parser.
app.use(BodyParser.urlencoded({extended:true}));
FormData sends the request with Content-Type set as multipart/form-data.
As your bodyparser can't parse such content type, you should try to send the data either as application/json or application/x-www-form-urlencoded.
See MDN docs of FormData.
You can use jquery's serialize method to get the urlencoded string.
I need to create a Node server only for receiving POST requests. With the information in the body of the request, I need to create a system call. How do I do so? So far, I only have:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser);
app.post('/', function(req, res){
console.log('POST /');
console.dir(req.body);
});
port = 3000;
app.listen(port);
console.log('Listening at http://localhost:' + port)
However, when I make a POST request to 127.0.0.1:3000, the body is undefined.
var request = require('request');
request.post(
'127.0.0.1:3000',
{ form: { "user": "asdf" } },
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
You've got a middleware problem here. The express.bodyparser() middleware is deprecated in Express 4.x. This means you should be using the standalone bodyparser middleware.
Oddly enough, you're importing the correct middleware by doing:
var bodyParser = require('body-parser');
However, you should be using it differently. Take a look at the docs and the example given:
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
var app = require('express')();
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded
app.use(multer()); // for parsing multipart/form-data
app.post('/', function (req, res) {
console.log(req.body);
res.json(req.body);
})
In the newest version of express, express.bodyParser is not used. See the reference