Now I send data to express server as query param. But, I instead send the data to express server as payload.
How do I send payload data to express server? And how do I get the payload data from express server? Can anyone clear my doubts?
Here is my code,
// http request code
var http=new XMLHttpRequest();
http.open('post','localhost:9090/putData');
http.onload=function(){
if (this.status >=200 && this.status <300){
console.log(this.response);
}
};
var payload = {
data: 'Something'
}
http.send(payload);
// server.js
app.use(bodyParser.json({limit: '50mb'}));
app.use('/putData', function(req, res){
console.log(req.body); // empty object printed
})
What's wrong in my code.
You'll need to reference 'body' from the request object. Depending on the type, you can deserialize it with a parser. I use the npm package 'body-parser' to deserialize my objects to json. Set up the body parser in the express middleware as shown below
app.use(bodyparser.json({limit: '50mb'}));
Then you can use the req.body object in your following requests`
app.get('getBody', function(req, res){
console.log(req.body);
res.status(200);
});`
Related
My Code Returns Invalid Text When I Try To Do It.
app.post("/charge", (req, res) => {
console.log(req.body)
})
As the doc for req.body says:
req.body contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().
The following example shows how to use body-parsing middleware to populate req.body.
By default, the body of the request is not yet read from the incoming stream and therefore it is not yet parsed into req.body either. To get it read and parsed into req.body, you have to use some appropriate middleware that will do that for you (or you could do it manually yourself, but it's generally easier to use pre-written middleware that does the job for you).
Which middleware to use depends upon the type of the data in the body (urlEncoded data, JSON data or something else).
Here's the example from the doc:
var express = require('express')
var app = express()
app.use(express.json()) // for parsing application/json
app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.post('/profile', function (req, res, next) {
console.log(req.body)
res.json(req.body)
})
I'm currently teaching myself more about server code, specifically using Node.js and Express, and I'm having a lot of trouble with receiving and parsing a JSON object sent from a POST request. I have looked at numerous other posts (linked to below) and I can't figure out for the life of me what's going wrong. Here's what I've looked at:
Javascript: Send JSON Object with AJAX
Javascript : Send JSON Object with Ajax?
How do I consume the JSON POST data in an Express application
How do I consume the JSON POST data in an Express application
Send POST data using XMLHttpRequest
Send POST data using XMLHttpRequest
How do you extract POST data in Node.js?
How do you extract POST data in Node.js?
All of these are putting me on the right track, but I'm not quite there and thus looking for help. Here's the code I'm working with:
Send POST Request
var button = document.querySelector("#button");
button.onclick = function(){
console.log("Getting data from local server");
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:3000/data/test.json", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(JSON.stringify({"latitude": 41.2418, "longitude": -70.8898}));
};
Handle POST Request In Server
var http = require("http");
var fs = require("fs");
var express = require("express");
var app = express();
var path = require("path");
var bodyParser = require("body-parser");
var port = process.env.PORT || 3000;
//tells express where to find all the static files (HTML, CSS, etc) and load them into the browser
app.use(express.static(path.join(__dirname, '../client')));
//tells the application to use body-parser as middleware so it can handle post requests
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
//routing methods
//deal with incoming GET and POST requests to the server
app.get("/", function(req, res){
res.send("Submitted GET Request");
})
//only handles incoming POST requests to the test.json resource
app.post("/data/test.json", function(req, res){
console.info("Submitting POST Request to Server");
console.info("Request body: " + req.body);
//write the file
fs.writeFile(__dirname + "/../client/data/test.json", req.body,
function(err){
if(err){
console.error(err); //print out the error in case there is one
return res.status(500).json(err);
}
//resolve the request with the client
console.info("updated test.json");
res.send();
});
})
//tell the express object to create the server and listen on the port
app.listen(port);
console.log("Listening on localhost:" + port);
Whenever I try to print out the contents of "req.body" I get the output of "[object Object]". Any ideas?
EDIT:
My issue has been solved. I have changed
console.info("Request body: " + req.body);
To
console.info("Request body: " + JSON.stringify(req.body));
I also changed my Content-Type in my POST XMLHTTPRequest to "application/json" to help with formatting.
"[object Object]" is the default result of JavaScript's implicit toString operation, which it uses when trying to write a string representation of that object to the file.
Try writing JSON.stringify(req.data) to the file instead.
Also, on the client side – consider changing your Content-Type header to match:
xhr.setRequestHeader("Content-Type", "application/json");
If your post body is expected to be JSON, then change this line
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
To
xhr.setRequestHeader("Content-Type", "application/json");
There is a passport.js implementation which is being used for LDAP-auth which works. Now the next step is to encrypt the password on the client-side using Crypto-js as follows:
Client-side angular-js controller
$scope.authenticate = function () {
var auth = new login();
auth.username = $scope.username;
auth.password = CryptoJS.AES.encrypt($scope.password); //// HERE
auth.$save(function (response){
console.log(response);
},function(err){
console.log(err);
});
}
Server-side service
.....
.....
app.post('/login', passport.authenticate('ldapauth'), (req, res) => {
console.log("req.user: ",req.user);
req.session.username = req.user[ldap.username];
req.session.userModel = req.user;
res.status(200).send({"success": 'success'});
});
.....
On the server-side service before calling passport.authenticate with the request 'req' the aes encrypted password needs to be decrypted. How can that be implemented here? (The question is not about encryption but how to get data before it gets passed to passport.authenticate as request)
#Abhijay Ghildyal I don't think they understood your question. It is indeed possible to intercept the request before it gets passed to passport.authenticate(). What you'd want to do is to add this passage of code to your express.js or whichever file you did your express server implementation in. Also I am decrypting the request.body here instead of req.user since at that point of time the user is not yet logged in, however if it's different in your case then that's fine you can decrypt req.user the same way. (The variable app here is the name of your server i.e var app = express();)
app.use(function(req, res, next) {
if(req.url === '/login'){
//CryptoJS.AES.decrypt() is Assumed to be the decrypter function here.
req.body = CryptoJS.AES.decrypt(req.body);
console.log(req.body); //To view decrypted body
}
next();
});
That is it. This middleware function will be reached first before the passport.authenticate() function. Just make sure if you're applying this to req.body you add these lines of codes first, after importing the bodyParser (bodyParser = require('body-parser');) before the passage above.
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
This is my code:
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.get('/',function(req,res){
res.sendfile("index.html");
});
app.post('/login',function(req,res){
console.log(req.body)
var user_name=req.body.user;
var password=req.body.password;
console.log("User name = "+user_name+", password is "+password);
res.end("yes");
});
app.listen(3000,function(){
console.log("Started on PORT 3000");
})
I set a console in post method function but it displayed:
{}
User name = undefined, password is undefined
I couldn't get any data from response. I had lookup doc but I couldn't find any error. I don't still understand. What mistake did i make?
You should send your data using Postman with the content-type:application/json in the header. This will ensure that the server receives the data in JSON format.
I know what happens!
If I want to send data in form-data, here has good solution helps me:
Result is undefined when I use form-data in Postman
If I use x-www-form-urlencoded to send data, it's actually valid!
I find when postman send json data without content-type:application/json in headers, it's definitely error. Now, I have added it. It can be valid.
Thanks, everyone!
I just installed the latest versions of modules. I can not get any GET or POST variables. What i do wrong?
NODE: v0.12.2
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.body, null, 2))
});
app.listen(3000,function(){
console.log("Started on PORT 3000");
})
http://localhost:3000/?token=devvvvv GET returns:
you posted:
{}
Thanks for answers, but problem with POST does not solved...
POST token=as123ds on http://localhost:3000/ return empty array in req.body
How can i solve this?
You are submitting parameters via the query string and attempting to access them through the request body which in this case is empty.
The token parameter will be available in request.query like so:
app.use(function (req, res) {
res.setHeader('Content-Type', 'text/plain')
res.write('you posted:\n')
res.end(JSON.stringify(req.query.token, null, 2))
});
If you only plan to submit parameters in the query string you should not need to mount the body-parser middleware at all.
You should be using the req.query:
req.query
An object containing a property for each query string parameter in the route. If there is no query string, it is the empty object, {}.
api link
You are parsing JSON from the request, so the POST from client must have 'Content-Type': 'application/json' in HTTP header. If not, you'll have empty request.body at server side.
bodyparser module requires the http request's "Content-type" property equal to "application/json". It won't work for other values.
You have to check the request content type in the client, this link may help
Node (Express) request body empty
This is because bodyParser parses application/json,
application/x-www-form-encoded and multipart/form-data, and it selects
which parser to use based on the Content-Type.