nodejs- unable to fetch form data - node.js

I'm using Express JS (v 4.15.3) for building a node api.
I'm trying to fetch the values send from a form (via POSTman client). I'm not able to fetch it.
This is my form
with headers specified
Without headers
This is how I'm trying to fetch it:
router.post('/login',function(req, res, next) {
var email= req.body.email;
//var email= req.query.email; //also tried this
res.json({
value: email
});
});
I'm not getting error.
Note: I have included body parser.
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Can anyone tell me why I am not getting the value? Thanks!
This is my first attempt at learning Node JS.

Your code seems perfectly alright. Though the issue is with the way you are sending request from POSTman client.
When you are sending request using use form data, POSTman sends this request as multipart/form-data, which actually sends your data in the format as below:
POST /api/login HTTP/1.1
Host: localhost:3000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
----WebKitFormBoundaryE19zNvXGzXaLvS5C
Content-Disposition: form-data; name="email"
example#example.com
----WebKitFormBoundaryE19zNvXGzXaLvS5C
For multipart/form-data requests you need to use multer middleware, if you really need file-uploads with your application. But for your case you can just send data without using use form data (un-check the use form data checkbox), and setting content-type header as:
Content-Type: application/x-www-form-urlencoded
So after all these modifications your raw web request should look something like below:
POST /api/login HTTP/1.1
Host: localhost:3000
Content-Type: application/x-www-form-urlencoded
Cache-Control: no-cache
email=example#example.com
The POSTman screen capture for building the request and response is as below:
The POSTman screen capture for Raw request and response is as below:
Hope this will help you.

Try to set Content-Type to application/json and in body in raw write in json format like this :
{
"email":"example#gmail.com"
}
Here are the images which you can refer.
Don't forget to upvote the answer if you find it helpful.

Related

Apiary multipart/form-data

I have tried creating an Apiary request with multipart/form-data, which seems alright, except when I try actually sending it via the console on Apiary to an existing (and functional) endpoint written in Node.js using async-busboy I'm getting back
{
"message": "Unexpected end of multipart data"
}
The Apiary Blueprint for this request looks like this:
+ Request
+ Headers
Content-Type: multipart/form-data; boundary=BOUNDARY
+ Body
--BOUNDARY
Content-Disposition: form-data; name="name"
John Doe
--BOUNDARY
Content-Disposition: form-data; name="email"
john.doe#email.com
--BOUNDARY--
I'd like to know if there is any problem that can be fixed in the Blueprint snippet or if this is even supported, or if the problem might be in the server itself (but the server works when I send a multipart post request from postman, curl and there are also few client implementations using it)

node.js server: HTTP POST body is empty

I am sending info from a wi-fi connected arduino device (cc3000) to an AWS server running express/node. I plan to eventually hook the endpoint up to SQS as a producer, but for now I am just trying to get a POST request to work. The problem is, I am on secure shell on my AWS and the body portion is empty as I see post requests stream in. However, the headers are present as I have sent them. My question is, where is the data going? Is this a formatting problem or something wrong with AWS?
Raw body of POST request (I am just using plain/text for now to see if I can get this to work):
POST /postdata/ HTTP/1.1
Host: *******************
User-Agent: Arduino/0.6.0
Accept: plain/text
Content-Length: 36
Content-Type: plain/text
{"temperature_c": "29.80"}
Again, the headers are in the JSON payload, but not the "temperature" portion.
Here is the endpoint:
app.post('/postdata', function (req, res) {
Sensor_data.create(req.body);
console.log(req.body);
});
The headers are present. This is intended to write to a mongoDB. If I do a cURL request from the command line, it writes successfully. For example, this works:
curl -v *************** -d "{temp_f=28.40&relative_humidity=45.40"
So if the headers are there, I know I am successfully writing something to the server. Where the heck is the data? Is this a formatting problem or something wrong with AWS?
## EDIT ########:
I double checked to make sure body-parser was set up. I had installed the middleware in my server.js as so:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
However, another issue has arisen. I have some code in this route to help me see what is going on by logging to console. I changed the POST request to application/json and know it is parsing because I had a small typo that I had to fix. However, once it started parsing correctly, nothing logged to console and nothing wrote to mongoDB. Any idea what is happening there? If the JSON is in fact being parsed, where is it being received on the server?
This issue was solved by setting app.use(bodyParser.urlencoded({ extended: false })); to be initialized with true and creating the post request with Accept and Content-Type to application/x-www-form-urlencoded. Hope this post helps some people as I have have seen quite a few posts with people struggling with this issue
It isn't clear whether you've set up the appropriate middleware to do the parsing. You'll find documentation here - in the first example you'd need the json parser, and in the second you'd need urlencoded (although there appears to be an extra leading { - a typo, perhaps?).
I am just using plain/text for now to see if I can get this to work
That's not going to work. The json-parsing middleware decides whether to try to parse based on the content-type - if you aren't honest, it doesn't know it should try to parse. Use application/json if you're going to send a JSON body.

Authenticate via POST request in Node.js

I'm trying to authenticate with a site through node by sending my username and password through a POST request, as that's how the login form seems to be doing it. When trying it out with Postman it works just fine and I'm redirected to the my dashboard.
Username and password fields are unfortunately not labeled as username and password, but as j_username and j_password.
This is the data Postman shows me (for reference):
POST /path/for/auth/request HTTP/1.1
Host: site.com
Cache-Control: no-cache
Postman-Token: b6656210-caeb-2b62-d6b6-e10e642b200b
Content-Type: application/x-www-form-urlencoded
j_username=myusername&j_password=mypassword
So I try this in node:
var request = require('request');
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'https://site.com/path/for/auth/request',
body: "j_username=myusername&j_password=mypassword"
}, function(err, res, body){
console.log(body);
});
But unfortunately it's coming back empty and err is set to null.
What could be going wrong here? Or is there a better way of authenticating with this resource? As far as I can tell Basic Auth through a header isn't possible here.
Thanks.
The site is probably sending you an HTTP 302 redirect, so that's considered success, which is why there's no error, but there's also no response body, which is why it's "empty". You'll want to look at the statusCode as well as the Location header in the response.

Empty req.body receiving text/plain POST request to node.js

Why can't I receive plain text sent in a POST request body?
The request made from a client browser:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/MyRoute/MySubRoute");
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xhr.send("hello!");
Using Express with my node server:
app.post('/MyRoute/MySubRoute', function(req, res) {
console.log("Received:"+require('util').inspect(req.body,{depth:null});
res.send();
});
Logged to the console I get:
Received:{}
I've tried with text/plain (no charset), with the same result. If I change my content type to application/json and pass a simple JSON string it works fine.
Summarising the above comments which answer the question:
The client's XMLHttpRequest is correct
On the server side, Express uses connect's bodyParser which by default only supports the following content types:
application/json
application/x-www-form-urlencoded
multipart/form-data
Because the content-type of text/plain is not implemented by Express, there is no method to wait for the body to be received before calling the app/post route.
The solution is to add the text/plain content type to Express as described here
Add
app.use(express.text())
You can read more about it here

how to support request or response bodies for application/json, application/x-www-form-urlencoded and multipart/form-data in nodejs

actually I am newbie, I want to use express in my web application, So I want support all the requests and response in my application should support
application/json, application/x-www-form-urlencoded and multipart/form-data
express is rather smart, and will automatically determine the header type, you can even use res.send(JSONObj) to send an object directly as JSON. If you want to manually set the header you can do so by using res.setHeader('Content-Type', 'application/json') before you send any data.

Resources