Retrieve body data node express - node.js

I'm trying to retrieve body data but I only receive undefined on my terminal, dunno how/where to retrieve the "email". I've googled it a bit but can't seen to find the answer.
Here's the app.js file:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
//routes which should handle request
app.post("/orders", (req, res, next) =>{
console.log(req.body.email);
res.json(["Orange", "Apple", "Banana"]);
});
//export app
module.exports = app;
And here's the server.js file:
const http = require('http');
//import app.js file
const app = require('./app');
//define port to be used
const port = process.env.PORT || 3100;
const server = http.createServer(app);
server.listen(port, () =>{
//print a message when the server runs successfully
console.log("Success connecting to server!");
});
I want to receive the "name" data and use it in a function to return a json. I'm using postman to send post requests with one key only, named "email". Postman receives the Json test data "Orange, Apple, Banana" that I have coded, though.

For x-www-form-urlencoded your example should work fine (just choose it in Postman under the body tab).
If you want to POST data (e.g. with files) as multipart/form-data you can install the multer middleware and use it in your app: app.use(multer().array())
// File: app.js
const express = require('express');
const bodyParser = require('body-parser');
const multer = require('multer');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(multer().array());
//routes which should handle request
app.post("/orders", async (req, res, next) =>{
console.log(req.body.email);
res.json(["Orange", "Apple", "Banana"]);
});
//export app
module.exports = app;
This works with:
curl --location --request POST 'localhost:3100/orders' \
--form 'email=john#example.com'
and
curl --location --request POST 'localhost:3100/orders' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'email=john#example.com'

Related

Express post request gives {}

So, when i make a Post request to the ExpressJS api with postman (localhost:8080?test=test), i should get this from the api: {test: test} or something right? But i get this: {}.
Heres my code:
Api:
const express = require('express');
const http = require('http');
const path = require('path');
const app = express();
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
app.use(cookieParser())
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json())
app.use(express.static(__dirname + '../../../src/'));
app.get('/*', (req,res) => res.sendFile(path.join(__dirname)));
const server = http.createServer(app);
server.listen(port,() => {
console.log('Running...');
})
app.post('/', function(req,res){
let data = JSON.stringify(req.body);
console.log(data);
res.send(data)
})
Can you help me?
Edit:
Printscreen
Inside post endpoint you are console logging req.body which is actually {}. According to the endpoint you are receiving data as query params. Therefore you have to use req.query instead of req.body to capture the data.

Node JS - can't send data from Postman

I solved it, it was a problem with req.body empty
==
I trying to test this route but the data I send is not received. I tried Postman and a VC extension, same problem.
I send this data and I expected it to be available in req.body
{
"username": "OPK"
}
http://prntscr.com/tn722o
And header is set correctly to application/json
http://prntscr.com/tn74on
I do however get this error when I try rest client extension:
Header name must be a valid HTTP token ["{"]
app.js
const express = require("express")
const app = express()
const userRouter = require("./routes/userRoute")
const dotenv = require("dotenv")
dotenv.config()
mongoose.connect(process.env.CONNECTIONSTRING, {
useUnifiedTopology: true,
useNewUrlParser: true,
})
app.use(express.urlencoded({ extended: false }))
// app.use(express.json())
app.use("/user", userRouter)
app.listen(process.env.PORT)
useRoute.js:
const express = require("express")
const router = express.Router()
const userController = require("../controllers/userController")
router.post("/signup", userController.signUp)
module.exports = router
userController.js
const mongoose = require("mongoose")
const userModel = require("../models/userModel")
exports.signUp = (req, res) => {
const { username, email, password, passwordAgain } = req.body
return res.status(422).json({ username: username })
}
I suggest you to update your Postman to the latest version and install it as a separate application, not as extension for Chrome.
To check if your server method works in general you can send this request via curl:
curl --location --request POST 'http://localhost:5000/user/signup' \
--header 'Content-Type: application/json' \
--data-raw '{"username": "OPK"}'
You might need to use body-parser with Express.js to handle POST requests, that is if you're not using express#4.16.0 or greater.
npm instal --save body-parser
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())

Problems POSTing json to Node/Express server from Axios/React

I'm current working on a web application using Node.js with Express in the back-end and React.js in the front end. In attempting to post user data to the Node server, through axios, I am running into an issue. When I make a post with the x-www-form-urlencoded content type, the front end will post to the server but the entire JSON of the posted data appears in the key field of the first element. When I change the content type to json it stops posting anything from the front end. I have tried cUrling to the server, and curling a JSON post will get accepted by the server.
React code to post to server
handleSubmit()
{
var form=this;
var axiosConfig = {
headers: {
'content-type': 'application/json; charset=utf-8'
}
}
axios.post('http://localhost:8080/api/login/', {
'username': form.state.username,
'password': form.state.password
}, {headers: {'content-type': 'application/json'}});
};
Server code for api endpoint
//From server.js
const express=require('express');
const session=require('express-session');
const bodyParser=require("body-parser");
const path = require('path');
var login = require('./routers/login')
var port = process.env.PORT || 8080;
var app=express();
app.use(session({'secret': 'thealphabetbackwardsiszyxwvutsrqponmlkjihgfedcba'}));
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
//...
app.use('/api/login', login);
//from login.js
/* Router for login system
When user attempts to log in, check their credentials
If the user successfully logs in, create a session
If user enters invalid credentials prompt them
*/
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const user = require("./../models/UserSchema")
mongoose.connect('mongodb://localhost/newt');
const express = require('express');
const router = express.Router();
router.get('/', function (req, res)
{
console.log("Test");
})
router.post('/', function(req, res)
{
console.log(req.body);
res.end();
})
// To create test user use path localhost:8080/api/login/testing
router.get('/test', function (req, res)
{
var db = mongoose.connection;
var test = new user({
username: "joesephschomseph",
email: "testUser#test.com",
fname: "Joe",
lname: "Schmoe"
})
test.save();
console.log("Created test user!");
});
module.exports = router
npm install --save const body-parser
in app.js include const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({ extended: false }));
app.use(bodyparser.json());
remove the single quotes from your 'username' and 'password'
console.log(req.body);

Post request sent by CURL gets parsed correctly but when sent from postman, I get undefined data

I am learning Node.js as a result I am setting up a authentication service. I have an issue parsing the body from post request.
This is my index.js file
const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const db = require('./queries')
const port = 3000
app.use(express.json());
app.use(bodyParser.json())
app.use(
bodyParser.urlencoded({
extended: true,
})
)
app.get('/', (request, response) => {
response.json({ info: 'Node.js, Express, and Postgres API' })
})
app.post('/login',function(req,res){
var username=req.body.username;
var password=req.body.password;
console.log("User name = "+username+", password is "+password);
res.end("yes");
});
This is printed on the console:
bash-3.2$ node index.js
App running on port 3000.
Username = undefined, password is undefined
But when i use CURL
curl --data "username=Jerry&password=jerry#example.com" http://localhost:3000/login
It works. Don't know why?
You have to change the postman header settings. Try changing the header content type value to application/json and change body to raw.

Strange Response from express server

I created a simple server using expressjs and have post method but I got strange response to post article and I don't know why it happened. Could anyone mind helping me?
my expected is a JSON format.
Here is my app.js file
const express = require('express');
const mongoose = require('mongoose');
const articleModel = require('./models/article');
const bodyParser = require('body-parser');
enter code here
const db = mongoose.connect('mongodb://0.0.0.0:27017/bbs-api');
const app = express();
const port = process.env.PORT || 3000;
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({extended:true}));
// support parsing of application/json type post data
app.use(bodyParser.json());
const bbsRouter = express.Router();
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.body);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.body);
});
app.use('/api', bbsRouter);
app.get('/', (req, res) => res.send('Hello World!'))
app.listen(port, () => console.log('Example app listening on port 8000!'))
My postman. I log request body out but it is not as my expectation.
if you are sending form data(application/x-www-form-urlencoded) the you can do
bbsRouter.route('/articles').post( (req, res) => {
console.log(req.params);
// const newArticle = new articleModel(req.body);
// newArticle.save();
// res.status(201).send(newArticle);
res.send(req.params);
});
You're sending the wrong request body via postman, your body should be JSON format, not form data
Try removing body-parser and use middlewares directly from express and set urlencoded to false:
app.use(express.urlencoded({extended:false}));
// support parsing of application/json type post data
app.use(express.json());
See here urlencoded option documentation

Resources