app.post request is not working and giving me error - javascript

I'm trying to build server side back-end code for my website.
I tried app.get request in postman and it worked but when I tried
app.post request in postman it didn't work and gave me errors.
I tried all the solution that was available online and I could understand (I'm Ubuntu user).
Error Screenshot that I get in Postman
The following image will show you the error and format I used in postman
Server.js File (main server file)
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const app = express();
const mongoose = require("mongoose");
require("dotenv").config();
mongoose.Promise = global.Promise;
mongoose
.connect(process.env.DATABASE, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
// // DB config
mongoose.set("useCreateIndex", true);
// const db = require("./config/keys").mongoURI;
// Connect to MongoDB
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cookieParser());
// Models
const { User } = require("./models/user");
//====================================================
// USERS
//====================================================
app.post("/api/users/register", (req, res) => {
const user = new User(req.body);
user.save((err, doc) => {
if (err) return res.json({ success: false, err });
res.status(200).json({ success: true, userdata: doc });
});
});
app.get("/", (req, res) => res.send("hello world"));
const port = process.env.PORT || 3002;
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
User Model file (models/user.js)
const mongoose = require("mongoose");
const userSchema = mongoose.Schema({
email: {
type: String,
requrired: true,
trim: true,
unique: 1
},
password: {
type: String,
requrired: true,
minlength: 5
},
name: {
type: String,
requrired: true,
maxlength: 100
},
lastname: {
type: String,
requrired: true,
maxlength: 100
},
cart: {
type: Array,
default: []
},
history: {
type: Array,
default: []
},
role: {
type: Number,
default: 0
},
token: {
type: String
}
});
const User = mongoose.model("User", userSchema);
module.exports = { User };

pass this has a raw data from postman and then call the post api
{
"email": "rohan#getMaxListeners.com",
"password":"pass#123",
"name":"sher",
"lastname":"lock"
}

Postman request should be like below.
{
"email": "rohit***#gmail.com",
"password": "password#123",
"name": "sher",
"lastname": "lock"
}

You are sending an invalid JSON.
Use this JSON for sending Request.
{
"email":"rohan3131313#gmail.com",
"password":"password#123",
"name":"sher",
"lastname:"lock"
}

Related

Unable to access object properties while doing a post request

I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.
I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting 'undefined'.
All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.
I am stumped on what to try next. Any suggestions would be appreciated.
Here is my server.js file
const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use("/posts", postsRoute);
app.listen( process.env.PORT || 5000, (err) => {
console.log(`listening on port ${process.env.PORT}`);
});
Here is my routes file
const express = require('express');
const router = express.Router();
const { allPosts, createPost } = require('../db/models/postModel');
router.get("/", async (req, res) => {
console.log(`req.title is: ${req.title}`);
try {
const posts = await allPosts();
res.send(posts);
} catch (err) {
console.log(err.message);
}
});
router.post("/create", async (req, res) => {
const newPost = req.body;
try {
const addingPost = await createPost(newPost);
console.log(`req.body is:${addingPost}`);
console.log(`req.body title:${addingPost.title}`);
console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
res.send (addingPost);
} catch (err) {
res.status(500).send(err.message);
}
});
module.exports = router;
Here is my Schema file
const mongoose = require('mongoose');
const { Schema } = mongoose;
const postSchema = new Schema({
author: {
type: String,
required: true
},
title: {
type: String,
required: true
},
content: {
type: String,
required: true,
},
tags: [String],
file: String,
likes: {
type: Number,
//We want to default to 0 likes
default: 0,
},
createdAt: {
type: Date,
default: new Date(),
},
});
const postModel = mongoose.model('Post', postSchema);
//Get all posts
const allPosts = async () => {
const posts = await postModel.find();
return posts;
};
//Create posts
const createPost = async (post) => {
const newPost = await postModel.create(post);
return newPost;
};
module.exports = { allPosts, createPost };
Console.log outputs in the Node REPL
I have included a picture showing what the console.log ouputs in the terminal. Hopefully this supports my question.

how to save data into mongodb using express?

Trying to create signin and signup using express and MongoDB. In postman the data is perfectly passed but couldn't save the data into mongoDB cluster.
IN this file connection to the db is created and also confused whether i am connected to the db or not in this file, I created schema for the user details to be provided
//Index.js
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const dotenv = require("dotenv");
dotenv.config();
const db = process.env.DATABASE;
mongoose.connect(db, { useNewUrlParse: true }, () =>
console.log("connected to db")
);
//midlewares
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
//User.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const userSchema = new Schema({
name: {
type: String,
max: 32,
required: true,
min: 6,
},
email: {
type: String,
required: true,
max: 32,
},
password: {
type: String,
max: 1022,
min: 8,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("User", userSchema);
//Auth.js
const router = require("express").Router();
const User = require("../model/User");
router.post("/register", (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
const name = {
name: req.body.name,
email: req.body.email,
};
res.send(user);
user.save();
});
module.exports = route[![enter image description here][1]][1]r;
Step 1
First, you should create a server after your MongoDB is connected. So, put your server logic inside mongoose.connect connect. This will assure that when yo u try to create a new user, MongoDB is already connected.
mongoose.connect(db, { useNewUrlParse: true }, () =>
console.log("connected to db");
//midlewares
app.use(express.json());
//importing routes
const authRoute = require("./routes/auth");
//route middle wares
app.use("/api/user", authRoute);
app.listen(3000, () => console.log("gg server is running"));
);
Step 2
Use create method to create new user document:
router.post("/register", async (req, res) => {
const user = await User.create({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
return res.status(200).json(user);
});

Insert API Call in mongodb

I have a problem to insert a API call with request in mongodb with mongoose. I am very new in this topic. Need your help!!! Here ist my test.js, how can i solve this problem any ideas. My target is to save the Api call from the url and then update it all 30 min but at the moment i was very happy when i could save the call. For all help i am very grateful.
When i start with node test.js then i get only the ids in mongodb not more.
const request = require('request');
const path = require('path');
const https = require('https');
const mongoose = require('mongoose');
const port = 3000;
const dbUrl = process.env.xxx || 'mongodb://localhost:27017/testingDB';
mongoose
.connect(dbUrl, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true,
useFindAndModify: false,
})
.then(() => {
console.log('Connection ready');
})
.catch((err) => {
console.log(err);
});
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
//Create a Schema
const coinSchema = new mongoose.Schema({
id: String,
coin_id: Number,
name: String,
symbol: String,
market_cap_rank: String,
thumb: String,
small: String,
large: String,
slug: String,
price_btc: Number,
score: Number,
});
//Create a Model with collection coins
const Coin = mongoose.model('Coin', coinSchema);
app.get('/testing', async (req, res) => {
const url = 'https://api.coingecko.com/api/v3/search/trending';
request({ url, json: true }, (error, response) => {
if (error) {
console.log(error);
} else {
Coin.insertMany(response.body.coins);
console.log(response.body.coins);
}
});
});
app.listen(port, () => {
console.log(`Server ready on port ${port}`);
});```
Try
request({ url: 'https://api.coingecko.com/api/v3/search/trending', json: true }, function (error, response, body) {
// ...
Coin.insertMany(body.coins.map(({ item }) => item));
});

Save data to MongoDB using NodeJS

I am trying to pass data to a MongoDB collection and it returns Cannot POST /courseweb/course/add
Before passing values through axios I tried postman (a google extension) to send data.
This is my server.js which is implemented with expressjs
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const Bundler = require("parcel-bundler");
const cors = require("cors");
const mongoose = require("mongoose");
const InstructorDB = require('./public/DBModels/InstructorDB');
const router = express.Router();
const bundler = new Bundler("./src/index.html");
app.use(cors());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bundler.middleware());
// app.use(express.static('./src'));
app.use("/courseweb", router);
mongoose.connect("mongodb://127.0.0.1:27017/courseweb", {
useNewUrlParser: true
});
const connection = mongoose.connection;
connection.once("open", () => {
console.log("Connected to MongoDB via 27017");
});
app.listen(3000, err => {
if (err) {
console.error(err);
process.exit(-1);
}
console.log("Application is running on port 3000");
});
app.get("/", function(req, res) {
res.sendFile("./dist/index.html");
});
router.route('/course/add').post((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
});
router.route('/courses').get((req, res) => {
// name of the course database model here
InstructorDB.find().count(function(err, count){
res.status(200).send(count);
});
});
And this is my InstructorDB.js which is a schema model by mongoose
const mongoose= require('mongoose');
const Schema = mongoose.Schema;
let InstructorDB = new Schema({
firstName: String,
lastName: String,
designation: String,
faculty: String,
contactNumber: Number,
email: String,
password: String,
isEnabaled: Boolean,
courses: [{courseID: String}]
});
module.exports = mongoose.model('InstructorDB', InstructorDB, 'InstructorDB');
And this is a screenshot and the response I get when I pass the values through postman. I have set header as content-type and application/json too
Can anyone tell me where I have gone wrong?
Make sure you send the right data via your post request and change the verb to post :
app.post('/course/add', (req, res) => {
if(req.body == null){
return res.status(400).send({message: 'bad request'});
}
let instructorDB = new InstructorDB(req.body);
instructorDB.save((err ,doc ) => {
if(err){
res.status(400).send({message: err});
}
res.status(200).send(`Added`);
});
});
You don't need router if you're going to put it in the same file.
try this syntax instead:
app.post('/coureweb/course/add',((req, res) => {
let instructorDB = new InstructorDB(req.body);
instructorDB.save().then(bookDB => {
res.status(200).send(`${bookDB} Added`);
}).catch((err) => {
res.status(400).send({message: err});
});
}));
then take out
app.use("/courseweb")

NodeJS: Why is email undefined during user registration?

I am developing an API using NodeJS with the functionality of user registration and login. When a user register, I get
"Error: WHERE parameter "email" has invalid "undefined" value" this
error."
I have checked similar question and answer here and tried every one of them, but none has worked for me.
app.js file
```
//use path module
const path = require('path');
//use express module
const express = require('express');
//use ejs view engine
const ejs = require('ejs');
//use bodyParser middleware
const bodyParser = require('body-parser');
//use mysql database
const mysql = require('mysql');
const app = express();
//Setting port number
const port = process.env.PORT || 619;
const mysqlConnection = mysql.createConnection({
host: 'localhost',
user:'root',
password: '',
database: 'home_automation_db'
});
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.locals.stuff = {
url : req.originalUrl
}
next();
});
//connecting to database
mysqlConnection.connect((err) =>{
if(!err)
console.log('DB connection successful');
else
console.log('connection failed \n Error: '+JSON.stringify(err, undefined, 2));
});
var Users = require('./controllers/lightController');
app.use('/users', Users);
//server listening
app.listen(port, () => {
console.log('Server is running at port '+port);
});
lightcontroller.js
```var bodyParser= require('body-parser');
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var generator = require('generate-password');
var nodemailer = require('nodemailer');
const bcrypt = require('bcrypt');
const cors= require('cors')
const jwt = require('jsonwebtoken');
const express =require('express')
const users = express.Router();
const User = require('../models/User');
users.use(cors());
process.env.SECRET_KEY = 'secret';
```
```
// Login controller
users.post('/register', function (req, res) {
const userData = {
user_name: req.body.username,
email: req.body.email,
password: req.body.password,
location: req.body.location,
house_number: req.body.house_number
}
User.findOne({
where: {
email: req.body.email
}
}).then(user => {
if (!user) {
bcrypt.hash(req.body.password, 10, (err, hash) => {
userData.password = hash
User.create(userData).then(user => {
res.json({ status: user.email + "registered" })
}).catch(err => {
res.send('error: ' + err)
})
})
} else {
res.json({ error: "user already exist." })
}
}).catch(err => {
res.send('error: '+err)
})
});
```
User model
const Sequelize = require('sequelize')
const db = require("../database/db")
module.exports = db.sequelize.define(
'user_tb',
{
user_id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
user_name: {
type: Sequelize.STRING
},
email: {
type: Sequelize.STRING
},
password: {
type: Sequelize.STRING
},
location: {
type: Sequelize.STRING
},
house_number: {
type: Sequelize.STRING
}
},
{
timestamps: false,
freezeTableName: true
}
)
As #messerbill said the most probable cause is the sending of data as undefined
Try adding config after post data to your post request on the client side so it sets proper content-type:
axios.post('http://localhost:9000/api/login', {
email: this.state.email,
password: this.state.password,
}, {
'content-type': 'x-www-form-urlencoded'
}).then(res => {
console.log(res);
if(res.status) {
console.log('User is logged in');
}
}).catch(err => console.log(err))

Categories