i am new to MERN framework
try to use postman to test my get and post request. but keep getting this error SyntaxError: Unexpected token b in JSON at position 3
here is my schema -------------------------
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstname: {
type: String,
required: true
},
lastname: {
type: String,
required: true
},
sex: {
type: String,
required: true
},
age: {
type: Number,
required: true
},
password: {
type: String,
required: true
},
admin: {
type: Boolean,
default: true
}
});
module.exports = User = mongoose.model("user", UserSchema);
here is my route---------------------
const express = require("express");
const router = express.Router();
const User = require("../../models/user");
router.get("/", (req, res) => {
User.find()
.sort({ age: -1 })
.then(users => res.json(users));
});
router.post("/", (req, res) => {
const newUser = new User({
firstname: req.body.firstname
});
newUser.save().then(user => res.json(user));
});
module.exports = router;
here is my server------------------
const express = require("express");
const mongoose = require("mongoose");
const users = require("./routes/api/users");
const app = express();
app.use(express.json());
const db = require("./config/keys").mongoURI;
mongoose
.connect(db, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.log("MongoDB Connected"))
.catch(err => console.log(err));
app.use("/api/users", users);
const port = 5000;
app.listen(port, () => console.log(`server started on port ${port}`));
please help!! stuck for whole day
You do not need express.json() for GET routes. So please try moving app.use(express.json()); to route file before POST request.
Also if you are using express version >= 4, please use app.use(bodyParser.json()) from body-parser package.
Related
Please help review my error. I have defined my user schema but it is still undefined. I have spent hours on this error but I cannot seem to find where did I go wrong.
Here's my schema and model:
const { model, Schema } = require("mongoose");
const userSchema = new Schema({
username:String,
employeeId: String,
accessLevel: String,
role: String,
company: String,
password: String,
email: String,
createdAt: Date,
});
module.exports = model("User", userSchema);
Here's controller:
const User = require("../models/user");
const registerUser = (req, res, next) => {
let user = new User({
username: req.body.username,
employeeId: req.body.employeeId,
accessLevel: req.body.accessLevel,
role: req.body.role,
company: req.body.company,
password: req.body.password,
email: req.body.email,
createdAt: new Date(),
});
module.exports = {
registerUser
};
Here's connection to DB and server:
const express = require("express");
const mongoose = require("mongoose");
const { MONGODB } = require("./config");
const userRoute = require("./routes/userRouter");
const PORT = process.env.PORT || 4000;
mongoose
.connect(MONGODB, { useNewUrlParser: true, useUnifiedTopology: true })
.then(console.log("Database connected"))
.catch((err) => {
console.log(err);
});
const server = express();
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
server.use("/api/user", userRoute);
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.listen(PORT, () => console.log(`Server is listening on ${PORT}`));
Here's router:
const express = require("express");
const usersControllers = require("../controllers/usersControllers");
const router = express.Router();
router.post("/registeruser", usersControllers.registerUser);
module.exports = router;
Post request on Postman: http://localhost:4000/api/user/registeruser
body:
{
"username": "Susan",
"employeeId": "12345",
"accessLevel": "Account Admin",
"role": "MC - Engineer",
"company": "Mello",
"password": "Choochootrain",
"email": "susan#hotmail.com"
}
Try to change the order of your middleware declarations:
const server = express();
server.use(express.urlencoded({ extended: true }));
server.use(express.json());
server.use("/api/user", userRoute);
server.use((err, req, res, next) => {
console.error(err);
res.status(err.statusCode).json(err);
});
To start with I am noob in node.js and MongoDb and working with tutorial with Lama Dev social media as a basic project kindly help
in Postman
error 404 is coming
where in the video it's 200 ok
I have copied main code for 100-1000 times help
This Is my auth.js file
//auth.js
const router = require("express").Router();
const User = require("../models/User");
//register
router.post("/register", async (req, res) =>{
const newUser = new User({
username: req.body.username,
email: req.body.email,
password: req.body.password,
});
try{
const user = await newUser.save();
res.status(200).json(user);
} catch(err) {
console.log(err);
}
});
module.exports = router;
This Is my User.js file in models folder
//User.js
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
username: {
type: String,
require: true,
min: 3,
max: 20,
unique: true,
},
email: {
type: String,
required: true,
max: 50,
unique: true,
},
password: {
type: String,
required: true,
min: 6,
},
profilePicture: {
type: String,
default: "",
},
coverPicture: {
type: String,
default: "",
},
followers: {
type: Array,
default: [],
},
followings: {
type: Array,
default: [],
},
isAdmin: {
type: Boolean,
default: false,
},
}, {timestamps: true});
module.exports = mongoose.model("User", UserSchema);
This Is my index.js file
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const dotenv = require("dotenv");
const helmet = require("helmet");
const morgan = require("morgan");
const userRoute = require("./routes/users");
const authRoute = require("./routes/auth");
dotenv.config();
mongoose.connect(process.env.MONGO_URL, ()=> {
console.log("MongoDb Connected");
});
//middleware
app.use(express.json());
app.use(helmet());
app.use(morgan("dev"));
app.use("/api/users", userRoute);
app.use("/api/auth", authRoute);
app.listen(8800, ()=>{
console.log("Backhend server is running");
})
And this is a screenshot of postman
Postman ScreenShot Click here
Your POSTMAN screenshot shows your HTTP verb being GET, but the route your registered is using POST. Try changing the verb in POSTMAN.
I am using Nodejs, MongoDB and Mongoose and while making a POST request I am getting error:
POST http://localhost:3000/subscribers
Content-Type: application/json
{
"name": "Lucky",
"subscribedToChannel": "Dev Tech"
}
Error: {
"message": "Subscriber validation failed: name: Path name is required., subscribedToChannel: Path subscribedToChannel is required."
}
The code snippet is mentioned below:
server.js
const express = require('express')
const app = express()
const mongoose = require('mongoose')
mongoose.connect(mongodb://localhost/subscribers, { useNewUrlParser: true })
const db = mongoose.connection
db.on('error', (error) => console.error(error))
db.once('open', () => console.log('Connected to Database'))
app.use(express.json())
const subscribersRouter = require('./routes/subscribers')
app.use('/subscribers', subscribersRouter)
app.listen(3000, () => console.log('Server Started'))```
---------------------------------------------------------------------------------------------------
routers/subscribers.js
const express = require('express')
const router = express.Router()
const Subscriber = require('../models/subscriber')
// Creating one
router.post('/', async (req, res) => {
const subscriber = new Subscriber({
name: req.body.name,
subscribedToChannel: req.body.subscribedToChannel
})
try {
const newSubscriber = await subscriber.save()
res.status(201).json(newSubscriber)
} catch (err) {
res.status(400).json({ message: err.message })
}
})
module.exports = router
----------------------------------------------------------------------------------------------------
models/subscriber.js
const mongoose = require('mongoose')
const subscriberSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
subscribedToChannel: {
type: String,
required: true
},
subscribeDate: {
type: Date,
required: true,
default: Date.now
}
})
module.exports = mongoose.model('Subscriber', subscriberSchema)
[1]: https://i.stack.imgur.com/rHf38.jpg
Use bodyParser above app.use(express.json())
Like : app.use(bodyparser.urlencoded({ extended : false }))
I created a simple node/express api connected to mongo atlas, i try to send post requests to add new data to the database with rest client extension in vscode but keep on running into the above error not sure where I have messed up in my code
main server file with middleware
const express = require("express");
const app = express();
const coolapi = require("./api/coolapi");
const dotenv = require("dotenv");
const mongoose = require("mongoose");
dotenv.config();
mongoose.connect(process.env.DB_ACCESS, { useUnifiedTopology: true }, () => {
console.log("DB connected");
});
app.use(express.json());
app.use("/api/coolapi", coolapi);
app.listen(3000, () => {
console.log("server is running");
});
File with express Router
const express = require("express");
const router = express.Router();
const coolioObj = require("../models/CoolModel");
router.post("/signup", (request, response) => {
const coolPerson = new coolioObj({
username: request.body.username,
email: request.body.email,
password: request.body.password,
});
coolPerson
.save()
.then((data) => {
response.json(data);
})
.catch((error) => {
response.json(error);
});
});
module.exports = router;
file with mongoose schema
const mongoose = require("mongoose");
const coolioSchema = mongoose.Schema({
username: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("coolioDB", coolioSchema);
request being sent
POST http://localhost:3000/api/coolapi/signup http/1.1
Content-Type: application/json
{
"username":"samthingsoweto",
"email":"sams#amapiano.co",
"password":"KabzaDaSmall",
}
JSON arrays doesn't support a comma after the last item. That is the cause of the error. Delete the last comma in all JSON arrays.
date: {
type: Date,
default: Date.now,
}, <---
{
"username":"peoplefrom",
"email":"peopleperson#email.com",
"password":"peoplepassword123", <---
}
I'm trying to set up an API with MongoDB (Mongoose) with a JWT authentication. I am at the first step where I create an user in the DB.
But I encounter a problem : the async/await taking so long and never ending, while the user is not created on DB. I don't know why.
I'm testing with POSTMAN for requests. For information, when I'm starting my app, I'm getting the "connected to db !" who appear correctly.
Can someone help me please ?
app.js
'use strict';
const express = require("express"),
app = express(),
authRoutes = require('./routes/auth'),
externalRoutes = require('./routes/web'),
database = require('./database/db'),
bodyParser = require("body-parser"),
mongoose = require('mongoose')
;
require('dotenv').config();
var options = { useNewUrlParser: true, useUnifiedTopology: true };
mongoose.connect("mongodb+srv://user:password#host.mongodb.net/test?retryWrites=true&w=majority", options, () => console.log('connect to db !'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use('/api/user', authRoutes);
app.use('/', externalRoutes);
app.listen(8080);
auth.js
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
const savedUser = await user.save((error, userDoc) => {
if (error) return res.status(400).send(error);
});
res.send({
user: savedUser._id
});
}).post('/login', (req, res) => {
});
module.exports = router;
User.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
min: 6,
max: 255
},
email: {
type: String,
required: true,
max: 255,
min: 10
},
password: {
type: String,
required: true,
max: 1024
},
createdAt: {
type: Date,
default: Date.now()
},
updatedAt: {
type: Date,
default: Date.now()
},
});
module.exports = mongoose.model('User', userSchema);
In Auth.js do this instead
const router = require('express').Router();
const User = require('../database/schemas/User');
router.post('/register', async (req, res) => {
const user = new User({
name: req.body.name,
email: req.body.email,
password: req.body.password,
});
try {
// if you are using await, don't pass it a callback
const savedUser = await user.save();
return res.send({
user: savedUser._id
});
} catch (error) {
// use try/catch to handle error instead of error first parameter in callback
return res.status(400).send(error);
}
}).post('/login', (req, res) => {
});
module.exports = router;
Here is a link to the documentation that shows you how to correctly use the save method. https://mongoosejs.com/docs/api.html#model_Model-save