Express 4.17 req.body is empty - node.js

I'm hoping you can help me out here because after trying over a dozen s/o solutions and reading the express docs several times, I'm stumped. I'm building a Node app that will (in the end) accept a POST from the front end app, persist it to Mongo then allow back end users to manipulate the data. I am just getting going, trying to get the POST route working and have this so far:
app.js:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use("/", router);
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
index.js (routes...plan on changing the name)
const express = require('express');
const router = express.Router();
const appDataController = require('../controllers/appDataController');
router.post('/submit', appDataController.createAppData);
module.exports = router;
and appDataController.js:
const mongoose = require('mongoose');
const AppData = mongoose.model('AppData');
exports.createAppData = (req, res) => {
let reqData = req.body;
console.log(reqData);
res.send(reqData);
}
Simple enough, really, but when I grab Postman and set up a request using body/raw/json and send
{
"name": "John",
"age": "21"
}
I always see that body is undefined. From everything I've seen, I'm not doing anything wrong, but the result clearly indicates otherwise...What is it that I've missed?

Its because your using your express.json middleware after the routes, change this:
const express = require("express");
const cors = require("cors");
const mongoose = require('mongoose');
const AppData = require("./model/AppData");
const uri = "mongodb://localhost:27017/lunch"
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
const connection = mongoose.connection;
const router = require("./routes/index");
const PORT = 3005;
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use("/", router); // this need to be here
connection.once('open', () => {
console.log('👍Successfully connected to MongoDB👍');
});
app.listen(PORT, function () {
console.log(`🚀The Backend Server is up and running on port ${PORT}🚀`);
});
first comes the middlewares and then the routes(depends on the middleware your using ofcurse).

You should also include urlencoded option to get the body on x-www-form-urlencoded body for POST requests.
const app = express();
app.use(cors());
app.use(express.raw({type: "application/json"}));
app.use(express.json({strict: false}));
app.use(express.urlencoded({extended: false})); // include this line
app.use("/", router);

Related

Hi, I am using Express with MongoDb, Whenever I make a post request, it shows that message (model made using mongoose) is not a constructor

Whenever I make a post request, it shows that message is not a constructor. Here message is a model that I made using mongoose.
And I am exporting this model through
module.exports = message and using this exported model in form_post.js file
my app.js file
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
const port = 3000;
const form_display = require('./routes/form_display');
const form_post = require('./routes/form_post');
app.use(express.urlencoded({ extended: false }))
app.use(express.json())
//Backend Connection
mongoose.connect("mongodb://127.0.0.1:27017/sudeepkart", {
useNewUrlParser: true,
useUnifiedTopology: true,
});
var db = mongoose.connection;
db.once("open", function () {
console.log("We are Connected !!");
});
// Pug Specific
app.set('view engine', 'pug') //Setting View Engine as Pug
app.set('views', path.join(__dirname, 'views')) //Setting views directory so that pug files can be fetched from he views directory
// Express Specific
app.use(form_display);
app.use(form_post);
app.use('/static',express.static('static'))
app.use((req, res, next)=>{res.status(404).send('<h2>Error Page Not found</h2>')});
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`);
})
my form_post.js file
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Message = require('../models/message.model')
const port = 3000;
router.use(express.urlencoded({ extended: false }))
router.use(express.json())
router.post('/message', function (req, res) {
// Creating New Object
var newMsg = new Message(req.body);
newMsg.save(function (err, msg) {
});
res.send('Your message has been successfully submitted');
})
module.exports = router;
my models/message.model.js file
const mongoose = require('mongoose');
// New Schema and New Model
var message_schema = new mongoose.Schema({ "id":String, "message":String });
var message = new mongoose.model("message_model", message_schema); // in other words model is a synonym for collection
module.exports = message;
Try destructuring it:
const {message} = require('../models/message.models')
MDN Documentation for destructuring
To answer your comment question, because you're trying to import Message while only exporting message. On your module.exports, I would reccomend always doing module.exports = {variable1, function2} etc, so you can destructure it and you can easily debug any issues (and stop confusion with variables too!)

The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` is a string

I'm trying to connect my api to Digital Ocean to prepare for deployment and when trying to connect to the database I get the following error "UError: The uri parameter to openUri() must be a string, got "undefined". Make sure the first parameter to mongoose.connect() or mongoose.createConnection() is a string." My server still connects to Digital Ocean as well. the api has worked perfect while in development as well.
Below is the db.js file
const mongoose = require('mongoose');
const connectDB = async () => {
const conn = await mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useCreateIndex: true,
useFindAndModify: false,
useUnifiedTopology: true,
});
console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold);
};
module.exports = connectDB;
And below is the server.js file
const path = require('path');
const express = require('express');
const dotenv = require('dotenv');
const morgan = require('morgan');
const colors = require('colors');
const fileupload = require('express-fileupload');
const cookieParser = require('cookie-parser');
const mongoSanitize = require('express-mongo-sanitize');
const helmet = require('helmet');
var xss = require('xss-clean');
var rateLimit = require('express-rate-limit');
var hpp = require('hpp');
var cors = require('cors');
const connectDB = require('./config/db');
const errorHandler = require('./middleware/error');
// Load env files
dotenv.config({ path: './config.config.env' });
// Connect to Database
connectDB();
// Route files
const bootcamps = require('./routes/bootcamps');
const courses = require('./routes/courses');
const auth = require('./routes/auth');
const users = require('./routes/users');
const reviews = require('./routes/reviews');
const app = express();
// Body Parser
app.use(express.json());
// Cookie parser
app.use(cookieParser());
// Dev logging middleware
if (process.env.NODE_ENV === 'development') {
app.use(morgan('dev'));
}
// File uploading
app.use(fileupload());
// Sanitize data
app.use(mongoSanitize());
// Set security headers
app.use(helmet());
// Prevent XSS attacks
app.use(xss());
// Rate Limiting
const limiter = rateLimit({
windowMs: 10 * 60 * 1000, // 10 minutes
max: 100,
});
app.use(limiter);
// Prevent http param pollution
app.use(hpp());
// Enable CORS
app.use(cors());
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Mount Routers
app.use('/api/v1/bootcamps', bootcamps);
app.use('/api/v1/courses', courses);
app.use('/api/v1/auth', auth);
app.use('/api/v1/users', users);
app.use('/api/v1/reviews', reviews);
app.use(errorHandler);
const PORT = process.env.PORT || 5000;
const server = app.listen(
PORT,
console.log(
`Server running in ${process.env.NODE_ENV} mode on ${PORT}`.yellow.bold
)
);
// Handle unhandled promise rejections
process.on('unhandledRejection', (err, promise) => {
console.log(`UError: ${err.message}`.red);
// Close server and exit process
server.close(() => process.exit(1));
});
I would appreciate any help than you.

nodejs connection fail to database

i'm trying to build a simple rest api based on node.js + mongodb
i'm using https://cloud.mongodb.com/ and my connection string is 1000% correct
i keep having this problem sometimes it work for me all the day no issue
and sometimes it doesn't wanna connect and i changed nothing in the code
anyone is having similar issues?
const mongoose = require('mongoose');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
require('dotenv/config');
app.use(bodyParser.json());
// Import routes
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
//mongodb connect
mongoose.connect(process.env.db_access, { useNewUrlParser: true, useUnifiedTopology: true },
() => {
console.log('connected');
}
);
//ROUTES
app.get('/', (req,res) => {
res.send('home boi');
});
//listening port
app.listen(3000);

How to render pages in nodejs with Router

how I can render my "firstsolution.ejs" page?
I have "server.js", "routes" folder which contain "firstsolution.ejs" and "views" folder which contain "solutions" folder and solutions folder contain "solution1.ejs"
enter image description here
server.js code is:
const fisrtsolution = require("./routes/firstsolution");
firstsolution.ejs code is:
const express = require("express")
const router = express.Router();
router.get("/", function(req, res) {
res.render("./solutions/solution1");
});
module.exports = router;
but when I try to enter "http://localhost:3000/firstsolution" I see "Cannot GET /firstsolution"
You forgot to include the route in the app :
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
require('dotenv/config');
const app = express();
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static("public"));
app.set("view engine", "ejs"); // IMPORT ROUTES
const firstsolution = require("./routes/firstsolution");
app.use('/firstsolution', firstsolution); // <--------- here
mongoose.connect( process.env.DB_CONNECTION,{ useUnifiedTopology: true,useNewUrlParser: true }, () => console.log("connected to DB") );
const port = 3000;
app.listen(port, () => console.log(server ${port}))
Try this, I hope my code will help you.
server.js code is:
app.use(require('./routes/firstsolution'));
firstsolution.ejs code is:
const express = require("express")
const router = express.Router();
router.get("/", function(req, res) {
res.render("solutions/solution1");
});
module.exports = router;

Express Router unable to route to another folder

I am trying to create a Node JS app with mongoDB. from main app.js I am trying to redirect to another folder named "services". Here is my folder structure -
Here is my app.js -
const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
const users = require('./userSchema')
const services = require('./services/index')
app.use('/services', express.static('/services'))
app.use(express.static('/'));
app.use(cors())
dotenv.config()
const port = 3000
mongoose.connect(process.env.DB_CONNECT,
{
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
})
.then(() => console.log('Connected to mongoDB'))
.catch(err => console.error('Could not connect to MongoDB..', err))
const jsonParser = bodyParser.json()
app.get('/allName', async (req, res) => {
let data = await users.find()
res.status(200).send(data)
})
app.listen(port, () => console.log(`Demo app listening on port ${port}!`))
Here is my index.js file inside services folder -
var express = require('express')
var router = express.Router()
router.get('/', function (req, res) {
res.send('Birds home page')
})
router.get('/about', function (req, res) {
res.send('About birds')
})
module.exports = router
While running http://localhost:3000/allName , it is working fine. But if i try to run http://localhost:3000/services, it is throwing Cannot GET /services. I am not able to fix this.
How to redirect to index.js from app.js when users trigger http://localhost:3000/services?
change
app.use('/services', express.static('/services'))
into
app.use('/services', services);
express.static is used to serve static files, looks like you wish to use a router and not return static files. This is why the server does not respond as you like
Yes, because you haven't properly added the reference of the service routes.
Remove express.static from the reference because you already have imported the service routes in a variable then just use it and it will work as expected.
Just a note. Express.static is used to load/use the static files like css or images or something like that.
Check the code below.
const express = require('express')
const mongoose = require('mongoose')
const dotenv = require('dotenv')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
const users = require('./userSchema')
const services = require('./services/index')
**app.use('/services', services)** // change this into your code.
app.use(express.static('/'));
app.use(cors())
dotenv.config()
const port = 3000
mongoose.connect(process.env.DB_CONNECT,
{
useUnifiedTopology: true,
useNewUrlParser: true,
useFindAndModify: false
})
.then(() => console.log('Connected to mongoDB'))
.catch(err => console.error('Could not connect to MongoDB..', err))
const jsonParser = bodyParser.json()
app.get('/allName', async (req, res) => {
let data = await users.find()
res.status(200).send(data)
})
app.listen(port, () => console.log(`Demo app listening on port ${port}!`))

Resources