Unable to post json data using postman in nodejs server - node.js

What am I doing wrong here? I saw somewhere that body-parser is now inbuilt in express in express, I tried that also still the same result.
app.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
require("dotenv/config");
const posts = require("./routes/posts");
const bodyParser = require("body-parser");
//middleware to use "/posts" whenever we go to posts
app.use("/posts", posts);
app.use(bodyParser.json()); //parsing json
//routes
app.get("/", (req, res) => {
//handle root
res.send("We are home");
});
//how do we start listening/connect to the server
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log("connected to DB!")
);
app.listen(3000);
Post.js
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now(),
},
});
module.exports = mongoose.model("Posts", PostSchema);
posts.js
const express = require("express");
let router = express.Router();
const Post = require("../models/Post");
//middleware
/*router.use(function(req, res, next){
console.log(req.url, "#", Date.now());
next();
})*/
router
.route("/")
.get((req, res, next) => {
res.send("hi get /posts");
})
.post((req, res, next) => {
console.log(req.body);
});
module.exports = router;
Terminal always shows that its undefined.
here's a screenshot of postman:

Yes bodyParser is included in the current versions of expressjs, and you can apply it like this:
app.use(express.json());
Also this middleware must be applied before using routes. So the order must be like this:
app.use(express.json()); //parsing json
app.use("/posts", posts);

Related

Node.js Cannot find get route

const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Observation = require("./schema/dreamWorld");
const bodyParser = require("body-parser");
const cors = require("cors");
app.get("/", (req, res) => res.send("Hello World"));
app.listen(3000, () => console.log("Server started on port 3000"));
app.use(cors, bodyParser.json());
app.get("/world", (req, res) => {
return res.status(200).json({ message: "HAppy?" });
});
const mongoDB = "mongodb://127.0.0.1/test";
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
in the above coding that I am testing in Postman! I can connect to "/" route and postman displays hello world! but when I search "/world" get route in postman it keeps on loading forever and does not fetch anything.
I have made sure server is running with correct Port number. what am I doing wrong here?
The body-parser no more necessary if use express V4.16 or later.
It is included into express.js.
More detail is explained in here.
This code will be works.
const express = require("express");
const mongoose = require("mongoose");
const Observation = require("./schema/dreamWorld");
const cors = require("cors");
const app = express();
app.use(cors())
app.get("/", (req, res) => res.send("Hello World"));
app.get("/world", (req, res) => {
return res.status(200).json({ message: "Happy?" });
});
const mongoDB = "mongodb://127.0.0.1/test";
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
app.listen(3000, () => console.log("Server started on port 3000"));

Postman keeps loading on sending POST request to an express route

I created a route and controller for my sign up.
Here's my route:
const express = require("express");
const router = express.Router();
const { signup } = require("../../controllers/auth");
router.post("/signup", signup);
module.exports = router;
And here's my controller:
exports.signup = () => (req, res) => {
const { name, email, password } = req.body;
res.json({
user: { name, email, password },
});
};
Inside my server.js file I register both:
const express = require("express");
const morgan = require("morgan");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const mongoose = require("mongoose");
require("dotenv").config();
// routes
const blogRoutes = require("./routes/blog");
const authRoutes = require("./routes/auth");
// app
const app = express();
// db
mongoose
.connect(process.env.DATABASE, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("DB connected!"));
// middlewares
app.use(morgan("dev"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(cookieParser());
// cors
if (process.env.NODE_ENV == "development") {
app.use(cors({ origin: `${process.env.CLIENT_URL}` }));
}
// routes middleware
app.use("/api", blogRoutes);
app.use("/api", authRoutes);
// port
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server is running on port ${port}`);
});
Now on my POSTMAN, I tried to put the data using POST http://localhost:8000/api/signup with the header and raw setup right.
{
"name": "SyRyan",
"email": "syryan#gmail.com",
"password": "brace1010"
}
The database is connected but the postman takes forever to load the json request back. Am I making any mistakes here? Please help!
I think that the problem is that signup is a function that returns a function, but it should be just a function that receives req & res as parameters:
exports.signup = (req, res) => {
const { name, email, password } = req.body;
res.json({
user: { name, email, password },
});
};

Undefined values in req.body

When I wanna make a POST req using Postman where I already set the content-type to application/json and I console.log the req.body.name or sth else it only returns undefined.
Here's the code:
index.js
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(
process.env.DB_CONNECT,
{ useNewUrlParser: true, useUnifiedTopology: true },
() => console.log("connected to mongoDB")
);
// Middleware
app.use(express.json());
// Routes
app.use("/api/user", authRoute);
// Run Server
const PORT = 5000;
app.listen(PORT, () => console.log(`server running on port ${PORT}`));
auth.js
const router = require("express").Router();
const User = require("../model/User");
router.post("/register", async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
console.log(req.body.name);
});
module.exports = router;
Since you are not using body parser and using only express.json() send requests as raw then pick JSON. The format that you should write looks like this:
{
"name": "Some name",
"lastname": "...."
}
Here is how your postman should look like:
Install Body parser as:
npm install --save body-parser
and then update your index.js file as:
var bodyParser = require('body-parser')
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies
extended: true
}));
just add these line after
// Middleware
app.use(express.json());
for example
// Middleware
app.use(express.json());
app.use(express.urlencoded{extended: true})
This express setting will allow you to parse html-body

Invalid Namespace specified Mongoose save collection

I am creating an application using expressjs, mongoose and ejs template engine.
I am facing an below mentioned issue while saving collection:
{"message":"Invalid namespace specified 'ecommerce\";.roleresources'"}
This is my entry script app.js file:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressLayout = require('express-ejs-layouts');
const config = require('./config');
const adminRoutes = require('./routes/admin');
const app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
app.set('views', 'views');
app.set('layout', 'layout/shop');
app.set("layout extractScripts", true)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressLayout);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminRoutes);
mongoose.Promise = global.Promise;
mongoose
.connect(config.mongodb_uri, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true } )
.then(result => {
console.log(result);
app.listen(config.port || 3000);
})
.catch(err => {
process.exit();
});
These are file config.js file:
const dotenv = require('dotenv');
dotenv.config();
module.exports = {
port:process.env.PORT,
mongodb_uri: process.env.MONGODB_URI
}
and this is my .env file:
PORT=3000
MONGODB_URI="mongodb://localhost:27017/ecommerce";
and model file is:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const roleResourceSchema = Schema({
name:{
type:String,
required:true
},
code:{
type:String,
required:true
},
url:{
type:String,
required:true
}
});
roleResourceSchema.index({name:1, code:1,url:1}, {unique:true});
module.exports = mongoose.model('RoleResource', roleResourceSchema);
and lastly my controller:
const RoleResource = require('../model/roleResource');
exports.getLogin = (req, res, next) => {
const resource = new RoleResource({
name:"All",
code:"all",
url:"*",
});
resource.save()
.then(data => {
res.send(data);
}).catch(err => {
res.status(500).send({
message: err.message
});
});
};
and if hard coded the mongodb url in my app.js then it's start working (modified app.js for working mongoose save)
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const expressLayout = require('express-ejs-layouts');
const config = require('./config');
const adminRoutes = require('./routes/admin');
const app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
app.set('views', 'views');
app.set('layout', 'layout/shop');
app.set("layout extractScripts", true)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(expressLayout);
app.use(express.static(path.join(__dirname, 'public')));
app.use('/admin', adminRoutes);
mongoose.Promise = global.Promise;
mongoose
.connect("mongodb://localhost:27017/ecommerce", { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex:true } )
.then(result => {
console.log(result);
app.listen(config.port || 3000);
})
.catch(err => {
process.exit();
});
How can I dynamically use the mongo db url from my .env file
It took me a while to resolved mine, but i finally did.
In you .env file, remove the quotes in MONGODB_URI.
Check sample below
PORT=3000
MONGODB_URI=mongodb://localhost:27017/ecommerce
The reason you are having the error:
It's simply because of the way you are writing the MongoDB URI in the .env file i.e MONGODB_URI="mongodb://localhost:27017/ecommerce";
The dotEnv package would parse the value for MONGODB_URI as mongodb://localhost:27017/ecommerce";, notice the double-quote(") and the semi-colon(;) at the end, they are not supposed to be there and that is what is causing the error.
The fix:
All you need to do is remove the semi-colon and everything should be fine: MONGODB_URI="mongodb://localhost:27017/ecommerce"

POST request working on localhost, but cannot POST to AWS

I can't solve my problem. I stuck in this issue for a long time, so now I'm asking you.
Here, this was my question before I posted.
I made a mistake that I didn't export module at that time.
Now, I tested in localhost, it works well.
However, if I test with postman, it doesn't work at all like bellow
If you guys have this experience and resolved, then please give me some tips to resolve this issue.
It's my app.js, routes/imgFiles.js and models/imgFiles.js
app.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 3000;
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const cookieParser = require('cookie-parser');
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, '../awesome-drill/dist')));
app.use(logger('dev'));
const appRoutes = require('./routes/app');
const imgRoutes = require('./routes/imgFiles');
const userRoutes = require('./routes/user');
app.use(imgRoutes);
app.use(userRoutes);
app.use(appRoutes);
app.use(cookieParser());
app.use((req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-Width, Content-Type, Accept');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
});
app.use(express.static('routes'));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '../awesome-drill/dist/index.html'));
});
app.listen(port, () => {
console.log(`Server is up on port ${port}`);
});
models/imgFiles.js
var express = require('express');
var router = express.Router();
var ImageFile = require('../models/imageFiles');
var multer = require('multer');
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../img/') // Set directory
},
filename: function (req, file, cb) {
cb(null, file.name) // Set file name
}
});
var img = multer({ storage: storage });
router.post('/uploadFiles',img.single('imgfile'), (req, res) => {
var imageFile = new ImageFile({
imgName: req.body.imgName,
imgType: req.body.imgType,
imgSize: req.body.imgSize,
imgContent: req.body.imgContent
});
imageFile.save((err, result) => {
if (err) {
return res.status(500).json({
title: 'An error occured',
error: err
});
}
res.status(201).json({
message: 'Img saved',
obj: result
});
});
});
module.exports = router;
models/imgFiles.js
var {mongoose} = require('../db/mongoose');
var uniqueValidator = require('mongoose-unique-validator');
var schema = mongoose.Schema({
imgName: {
type: String,
},
imgType: {
type: String,
},
imgSize: {
type: Number,
},
imgContent: {
type: String,
},
});
schema.plugin(uniqueValidator);
module.exports = mongoose.model('ImageFile', schema);

Resources