Cannot extract data from post request in node - node.js

I am sending a post request using axios in react to a nodejs backend and mysql database.
At the server side when I log req.body, it is undefined
and this is the params and query part when I log the request on server side:
params: {},
query: {},
This is inside the handlelogin method in react:
handleLogin=(event)=>
{event.preventDefault();
let formfields={...this.state.formfields};
axios.post('http://localhost:7000/api/login',{formfields
})
.then(res=>
{
console.log("response receieved");
})
.catch(err=>
{
console.log(err);
});
};
This is the node script( inside routes):
const express = require('express');
const exp = express();
const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));
exp.use(bodyParser.json());
const router = express.Router();
router.post('/api/login',(req,res,next)=>{
console.log('Inside login-serverside');
console.log(req);
});
module.exports = router;
I want to submit forms and pdf files(later) but I cannot access them on the server side.I can acces request.parameters when I make a get request.What is the issue here?
What are body,params and query used for, respectively and what is the difference?

I had not included body parser in my main server.js file
const bodyParser = require('body-parser');
exp.use(bodyParser.urlencoded({extended:false}));
After including this, it's working. I can now successfully use request.body and access the parameters passed in axios.post .
Though I am still confused about the use of params,query,data and body respectively.

Related

Node.js - how to use a raw request body using Express

so I was making a RESTful API and I wanted to be able to receive raw json data (so I can use my api for mobile too), then from there save the data into my database (mongoDB).
But you see, there is this problem which I can't seem to fix and its that I'm not able to use the raw data as a json.
The code is simple
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(parse.JSON(req.body));
//to convert it to json but this doesn't seem to work
})
PS. I'm using postman to send the request as raw format
const express = require('express')
const bodyParser = require('body-parser')
const app = express();
app.use(bodyParser.raw({inflate:true, limit: '100kb', type: 'application/json'});
app.post('/post', function(req, res){
res.send(JSON.parse(req.body));
})
inside the res.send you have to use JSON.parse() instead of parse.JSON() which will throw an error as it is not correct
if you want to read more about JSON.parse you can visit mdn docs

Unable to get values in NodeJs Express

I am trying to make post request but unable to get values in Postman; it's sending undefined. I am using Express version 4.17.1. Below is my code:
const express = require('express');
const router = express.Router();
const MongoClient = require('mongodb').MongoClient;
const dburl = process.env.URL;
router.use(express.json());
router.use(express.urlencoded({extended:true}));
router.post('/register',(req,res) => {
var data = {
name:req.body.name,
email:req.body.email,
};
res.send(data);
});
module.exports = router;
What am I doing wrong?
Your code snippet works, tested with express 4.17.1 on node 12.19.0. The issue must be from elsewhere.
Possible issues are:
The parser for router could have been overridden by the parser for app (assuming you're calling app.use(router) somewhere).
Can you move this to app level?
router.use(express.json());
router.use(express.urlencoded({extended:true}));

Openui5 jquery POST to Node.js Server contains empty request body on server side

I am setting up a sample App using Openui5 as frontend framework, Node.js & Express.js for backend API and MongoDB as database.
My JQuery Ajax post does not contain any body data when arriving at the backend.
I tried several of the solutions provided on stackoverflow, but none of them seems to work for me. MongoDB and Backend Server are running. Data fetching is also working with ui5 data binding to XML View.
controller.js:
onSave: function () {
//get user input from local json model
var oNewEmployee = this.getView().getModel("newEmp").getProperty("/newEmp"),
data = JSON.stringify(oNewEmployee),
url = 'http://localhost:3000/employee';
//do the post
$.ajax({
url : url,
dataType : 'json',
contentType : 'application/json',
data: data,
type : 'POST',
success: function(response){
console.log(response);
}
});
},
server.js:
var express = require("express");
var app = express();
var mongoose = require("mongoose");
var cors = require("cors");
app.use(cors());
mongoose.connect("mongodb://localhost/schichtplaner", { useNewUrlParser: true });
app.post("/employee", function (req, res) {
console.log(req.body);
});
app.listen(3000);
I keep getting undefined as output from console. Would be great if someone has an idea how to solve this.
You should use the body-parser npm module in order to read the POST request payload.
https://www.npmjs.com/package/body-parser

node js POST not getting data using React

I am submitting a form and the following gets called...
handleLogin(){
fetch('http://localhost:8080', {
method: 'post',
body: JSON.stringify({
username: this.state.username,
password: this.state.password
})
});
}
It makes a POST request to my restAPI. The request works, but the data is not passed...
app.post('/', function(req, res, next) {
console.log(req.body.username);
....
This prints out undefined, meaning password and username are not passed through the call. What am I doing wrong?
Express by default doesn't parse the body of the request. In order to enable parsing, you will need to use a middleware such as body-parser. You can find some information in the express docs.
Also, the client side needs to indicate that it's sending json data. That can be achieved with the Content-Type header. There is a pretty good tutorial about fetch() here. You can jump directly to the Request Headers section which is relevant for your question.
var express = require("express");
var app = express();
var bodyParser = require('body-parser');
const PORT = process.env.PORT || 7070;
const BASEURL = process.env.BASEURL || 'http://localhost/7070';
app.use(bodyParser.urlencoded({extended:true}));
app.listen(PORT, function() { console.log('Server running on'+BASEURL);
});

Why is request body undefined in one route?

I'm having some troubles trying to stablish a REST API with nodeJS and express. The following code defines two routes, "stores" and "user".
Surprisingly, the route to "/user" is working nice but when a request arrives to "/stores" the request body appears undefined. I've searched for a solution but nothing seems to work for me.
Both controllers have the same structure.
What am I doing wrong?
var express = require("express"),
app = express(),
bodyParser = require("body-parser"),
methodOverride = require("method-override"),
mongoose = require('mongoose');
// Connection to DB
mongoose.connect('mongodb://localhost/appDB', function(err, res) {
if(err) throw err;
console.log('Connected to Database');
});
// Middlewares
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
//Import models and controllers
var userModel=require("./models/user.js")(app,mongoose);
var storeModel=require("./models/store.js")(app,mongoose);
var usersController=require("./controllers/users.js");
var storesController=require("./controllers/stores.js");
//Router options
var router=express.Router();
router.route('/stores')
.get(storesController.getNearestStores);
router.route('/user')
.post(usersController.addUser);
app.use(router);
//Start server
app.listen(3000, function() {
console.log("Node server running on http://localhost:3000");
});
Thank you very much.
P.S.:First time with nodejs and express(and even mongo)
This is because there is no body on a GET request in the http standard. Only POST and PUT.
What you want to do instead is use a query string
get
/stores?location=mystore
this way on your callback you have access to req.query
req.query
{
location: 'mystore'
}
HTTP GET with request body
This gave me the solution, get requests don't accept parameters under HTTP standard.

Resources