req.body will not return a response - node.js

I've searched and tried other results, but none seem to render any results.
I'm trying to post data to the backend using postman as a test. The response is sending the 'success' message, but req.body returns an empty array every time I try. I'm using a node backend, with express and I'm trying to use routes. I've had success before, but for some reason I can't get it this time and my old code doesn't seem to work for this one. If I just log req, rather than req.body, I can see that the body is empty, the params are empty, but the url includes the params. I can post it, but it's rather long and I don't know if it's useful.
Here's the url I'm trying to hit: localhost:3000/?testParam=test&test=boop
app.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/blogTest', { useNewUrlParser: true });
mongoose.Promise = global.Promise;
const postsRoute = require('./routes/post');
app.use(postsRoute);
module.exports = app;
post.js
const express = require('express');
const router = express.Router();
const postModel = require('../models/post'); //not using this yet
router.get("/", function(req, res){
console.log("Getting Posts...");
postModel.find({}, function(err, posts){
if(err){
res.send("{'status': 'error', 'response': "+err+"}");
}
else if(posts.length < 1){
res.send("{'status': 'null', 'response': {}}");
}
else{
res.send("{'status': 'success', 'response': "+posts+"}");
}
});
});
router.post("/", function(req, res){
console.log(req.body);
res.send('success');
});
module.exports = router;
I'm expecting the console to log {'testParam': 'test','test':'boop'}
also, I've tried parsing req.body as json and stringifying it, but it causes the server to crash.

I think you are confused about http methods and how they work.
req.body is the POST request body, it is the data passed by the client when he sends a POST request to your api endpoint. If you are not sending any data in your POST request, then req.body will be empty.
In your example, to get the data from a request like localhost:3000/?testParam=test&test=boop you would need to look in req.params instead of req.body.

You need to try accessing the params variable of the request by code, trying to go through a log to find params might not be accurate therefore try
router.post("/", function(req, res){
console.log(req.params);
res.send('success');
});

Related

Cannot GET /api/signup - Using Postman and mongodb

I am very new to mongoose and I made one signup api and while testing it using POSTMAN I'm getting these weird error as well when I refresh my http://localhost:8000/api/signup I get a message saying "Cannot GET /api/signup" and in my postman post request I am seeing an error message that says "Cannot POST /api/signup".
How would I get rid of these messages that are being displayed?
I am following a tutorial so I tried copying and pasting the code from the GitHub to make sure everything was perfect but I was still seeing these error messages.
My app.js file is:
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
require("dotenv").config();
// import routes
const userRoutes = require("./routes/user");
// app
const app = express();
// db
mongoose
.connect(process.env.DATABASE, {
useNewUrlParser: true,
useCreateIndex: true
})
.then(() => console.log("DB Connected"));
// middlewares
app.use(morgan("dev"));
app.use(bodyParser.json());
app.use(cookieParser());
// routes middleware
app.use('api', userRoutes);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
my routes/users.js file is:
const express = require("express");
const router = express.Router();
const { signup } = require("../controllers/user");
router.post("/signup", signup);
module.exports = router;
my controllers/users.js is:
const User = require("../models/user");
exports.signup = (req, res) => {
console.log("req.body", req.body);
const user = new User(req.body);
user.save((err, user) => {
if (err) {
return res.status(400).json({
error
});
}
res.json({
user
});
});
};
I am hoping to see a response in my browser that does not display an image that image that says Cannot GET api/signup and I am hoping that Postman is able to return data from my api
It means there is no corresponding router setting to /api/signup
I think router.post("/signup", signup); should be router.post("/api/signup", signup);
This should work fine on PostMan.
But the browser url is a get request, so the request would still fail. You will need to send the post request by javascript then.
For example, something like :
fetch('/api/signup', {
method: 'POST',
body: 'signup data here'
})
.then(response => response.json());
Please let me know if the error still exist.
There is a minor bug
app.use('api', userRoutes);
change to
app.use('/api', userRoutes);
My issue was that when I installed mongoDB locally I had not properly installed it and was not using a /data/db folder. I was able to fully uninstall my older version of mongoDB and reinstall everything following this youtube tutorial: https://www.youtube.com/watch?v=MIByvzueqHQ

Unable to access the variable sent in POST

I sent a POST in my function to my server side (NodeJS), with the variable 'name'. 'name' is a string. However, I am unable to use this variable that I sent in the server-side.
I tried using req, req.body and req.body.name to access the variable I sent through POST. req gave me IncomingMessage {..}, req.body gave me {}, and req.body.name gave me undefined.
------Client Side------
var request = new XMLHttpRequest();
request.open("POST", "http://localhost:3000/addvoted", true);
request.send(name);
------Server Side------
app.post('/addvoted', function (req, res) {
var postBody = req.body;
console.log(postBody);
}
I expect the value of the variable name, which is a string, to be accessed in my server-side program.
I think this function send parameters via url,
try this code
req.query.name
replace name with variable name that you are sending
use npm body-parser
// create application/x-www-form-urlencoded parser
var bodyParser = require('body-parser')
var app = express()
var urlencodedParser = bodyParser.urlencoded({ extended: false })
// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
res.send('welcome, ' + req.body.username)
}``
Thank you.

NodeJS unable to get

new to NodeJS and I am trying to get a basic endpoint going. I actually have three different controllers, but one of them will not work. Here is my app.js
var express = require('express');
var app = express();
var db = require('./db');
var config = require('./config/config'); // get config file
global.__root = __dirname + '/';
var ApiController = require(__root + 'auth/ApiController');
app.use('/api/auth', ApiController);
var UserController = require(__root + 'user/UserController');
app.use('/api/users', UserController);
var AuthController = require(__root + 'auth/AuthController');
app.use('/api/auth/users', AuthController);
module.exports = app;
The UserController and AuthController work great but the ApiController:
//this controller handles api token
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
router.get('/apiToken') , function(req, res) {
console.log("received request at /apiToken");
res.status(200).send({ token: config.api.token });
};
module.exports = router;
When I try this in Postman you can see:
I know it has to be something really simple because the failing call is nearly identical to the working ones - but I just don't see it.
You have a coding mistake here with a closing paren in the wrong place on this line that happens to not make an interpreter error, but does not execute as intended:
router.get('/apiToken') , function(req, res) {
// here ^
So change this:
router.get('/apiToken') , function(req, res) {
console.log("received request at /apiToken");
res.status(200).send({ token: config.api.token });
};
to this:
router.get('/apiToken', function(req, res) {
console.log("received request at /apiToken");
res.send({ token: config.api.token });
});
FYI, there is no need to do res.status(200) as that is the default status already. You can just use res.send(...) and the status will be set to 200 automatically. You only need to use res.status(xxx) when you want the status to be something other than 200.
Also, running your code though something like jshint will often complain about these types of mistakes that (somewhat by accident) don't throw an interpreter error.

Request body is empty in Express route

I am building an API with Node.js, Express.js, and MongoDB. When I submit the form and use the req object in the route, the req.body object is empty.
req.body returns {} when I call the get_user function through the browser using postman at https://localhost:3000/users/0.
app.js:
var express = require('express'),
app = express(),
port = process.env.PORT || 3000,
bodyParser = require('body-parser');
var mongo_server = require('./server')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var routes = require('./routes/users')
routes(app);
app.use(function(req, res) {
res.status(404).send({url: req.originalUrl + ' not found'});
});
app.listen(port);
mongo_server.mongo_connection
module.exports = app;
userController.js:
var mongoose = require('mongoose'),
user = mongoose.model('users');
exports.get_user = function(req, res) {
console.log(req.body.id);
user.findById(req.body.id, function(err, user) {
console.log(req.body);
if(err)
res.send(err);
res.json(user);
});
};
userRoutes.js:
module.exports = function(app) {
var users = require('../controllers/userController');
app.route('/users/:userid')
.get(users.get_user);
}
I think you're confusing request parameters and request bodies. A request body is when you send information with the request like a payload, such as in a POST request when you send JSON to the server to, for example, create a new user:
{
"username": "jd123",
"email": "jd#example.com",
"name": "John Doe"
}
But in your case, you're looking for parameters, things passed through the URL like you've set up:
/users/:userid
That allows you to navigate to with a GET request:
/users/0
And then you can get the 0 as a string from req.params.userid not req.body.id. Request parameters and bodies are different. Parameters are for navigating to a varying route such as a user profile page, where the URL varies and reflects which route you want to go to by a user's ID.
Bodies are used for the payload of a request such as POSTing, PATCHing, and PUTing, giving information on what to update or create on the server.

How to capture (or log) the data of the Response object in Express?

I need to capture de sended data. I know how to set a middleware and capture the request and the response header.
I'm asking for capture the sent data.
I'm trying this:
var express = require('express')
var app = express();
var onFinished = require('on-finished')
app.listen(3000);
function logRes(res){
console.log('* captured response *')
console.log(res._header)
console.log(res.statusCode)
console.log(res.statusMessage)
console.log(res.body) // THIS DOES NOT WORKS!
}
app.use(function(req,res,next){
onFinished(res, function (err, res) {
logRes(res)
})
console.log('= captured request =');
console.log(req.method)
console.log(req.path)
console.log(req.query)
next();
});
app.get('/example',function(req,res){
res.header('Content-Type','text/plain');
res.end('example data');
});
Can any says to me how to look at the sent data in the line with the // THIS DOES NOT WORKS! comment?
You first need to include the third party middleware body-parser:
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.listen(3000);
app.use(bodyParser.json({ type: 'application/*+json' }));
app.use(function(req,res,next) {
console.log('= captured request =');
console.log(req.method);
console.log(req.path);
console.log(req.query);
console.log(req.body);
next();
});
app.get('/example',function(req,res) {
res.header('Content-Type','text/plain');
res.end('example data');
});
Check the repo and documentation here.

Resources