Reputation: 487
I know this has been asked multiple times, but I have been looking around and still can't find an answer to my problem.
Here is my code, I make sure to use and configure body parser before defining the routes. I'm only using .json() with bodyParser because right now I'm only testing a POST function, but I've even tried with app.use(bodyParser.urlencoded({ extended: true }));
var express = require('express'),
bodyParser = require('body-parser'),
app = express();
app.use(bodyParser.json());
app.set('port', (process.env.PORT || 5000));
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'))
});
app.post('/itemSearch', function(req, res) {
//var Keywords = req.body.Keywords;
console.log("Yoooooo");
console.log(req.headers);
console.log(req.body);
res.status(200).send("yay");
});
Here is how I use Postman to test this route.
and here is the response I receive
Node app is running at localhost:5000
Yoooooo
{ host: 'localhost:5000',
connection: 'keep-alive',
'content-length': '146',
'cache-control': 'no-cache',
origin: 'chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop',
'content-type': 'multipart/form-data; boundary=----WebKitFormBoundarynJtRFnukjOQDaHgU',
'user-agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36',
'postman-token': '984b101b-7780-5d6e-5a24-ad2c89b492fc',
accept: '*/*',
'accept-encoding': 'gzip, deflate',
'accept-language': 'en-GB,en-US;q=0.8,en;q=0.6' }
{}
At this point I would really appreciate any help. Thanks.
Upvotes: 32
Views: 56772
Reputation: 77
Hello You don't need body parser
const StringDecoder = require("string_decoder").StringDecoder;
_server.post("/users", function (req, res) {
const decoder = new StringDecoder();
let buffer = "";
req.on("data", function (data) {
buffer += decoder.write(data);
});
req.on("end", function () {
try {
console.log(JSON.parse(buffer));
res.json({ success: "ok });
} catch (e) {
console.log(e);
}
});
});
Upvotes: -1
Reputation: 56
Since you are sending the request as form-data, use urlencoded() middleware from express
or body-parser
.
bodyParser = require('body-parser').urlencoded({ extended: true });
app.post('/itemSearch', bodyParser, function(req, res) {
//var Keywords = req.body.Keywords;
console.log("Yoooooo");
console.log(req.headers);
console.log(req.body);
res.status(200).send("yay");
});
Upvotes: 0
Reputation: 97
After spending 2 days and hours I realized that I need to change postman : Text to JSON
If you're using express 16.4 and up, make sure you have :
const express = require("express");
require("dotenv").config({ path: "./config/.env" });
require("./config/db");
const app = express();
const userRoutes = require("./routes/user.routes");
app.use(express.json()); //this is the build in express body-parser
app.use( //this mean we don't need to use body-parser anymore
express.urlencoded({
extended: true,
})
);
//routes
app.use("/api/user", userRoutes);
// connect to the server
app.listen(process.env.PORT, () => {
console.log(`lestening port ${process.env.PORT}`);
});
Upvotes: 2
Reputation: 1841
I wanted to add an answer, as was seeming to have trouble getting sending as form-data
to work, even if I was adding Content-Type: multipart/form-data
to the Header (this was listed as correct header type in docs). I wonder if because using BodyParser in express, data has to come in as JSON raw. I swear I got form-data
to work before, alas.
Here's how I was able to get req.body
not to be empty:
Content-Type: application/json
Side note: interesting link to stack overflow article on all available header content type values.
raw
radio button is selected, and far right dropdown has JSON
selected:req.body
in my express app, I see printed:Upvotes: 6
Reputation: 1051
Try this
// create application/json parser
app.use(bodyParser.json());
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));
// parse an text body into a string
app.use(bodyParser.text({ type: 'text/plain' }));
// create application/x-www-form-urlencoded parser
app.use(bodyParser.urlencoded({ extended: false }));
Upvotes: 2
Reputation: 171
In my case, I solve it By Adding "type":"text"
to urlencoded
item int the exported collection json
file generated by postman. I observe it because there are some of my request is successfully done. The difference is the missing type
field in the json generated postman collection file. This problem also happen to my teammate.
before (failed request):
"body": {
"mode": "urlencoded",
"urlencoded": [
{
"key": "email",
"value": "{{userEmail}}"
},
{
"key": "password",
"value": "{{userPassword}}"
}
]
}
after (successful request):
"body": {
"mode": "urlencoded",
"urlencoded": [
{
"key": "email",
"value": "{{userEmail}}",
"type": "text"
},
{
"key": "password",
"value": "{{userPassword}}",
"type": "text"
}
]
}
I also write parser script in javascript language to handle it.
const fs = require('fs');
let object = require(process.argv[2]);
function parse(obj) {
if(typeof obj === 'string') return;
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
if(key === 'urlencoded') {
let body = obj[key];
for(let i = 0;i < body.length;i++) {
body[i].type = "text";
}
}
else parse(obj[key]);
}
}
}
parse(object);
fs.writeFile('ParsedCollection.json', JSON.stringify(object, null, '\t'), function(err){
//console.log(err);
});
Just run it in terminal node parser.js <json postman collection file path>
and it will output in ParsedCollection.json
file. After that import this file into postman.
Upvotes: 0
Reputation: 3359
After spending a few hours I realized need to change the Raw type in postman to JSON
Upvotes: 110
Reputation: 1213
AFAIK you need to use the Body-Parser : https://github.com/expressjs/body-parser
bodyParser = require('body-parser').json();
app.post('/itemSearch', bodyParser, function(req, res) {
//var Keywords = req.body.Keywords;
console.log("Yoooooo");
console.log(req.headers);
console.log(req.body);
res.status(200).send("yay");
});
Then try with PostMan setting the body as raw
json:
{
"test": "yay"
}
Upvotes: 30