SyntaxError: Unexpected token } in JSON at position 102 - node.js

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", <---
}

Related

Two databases in one nodejs project

I have two forms (signup form and an other form XYZ) in one Reactjs/Nodejs project.
How to post the two forms data to two different databases table, each one autonome ?
PS: I'm new in Nodejs, Thanks in advance.
My codes so far:
server.js:
const express = require('express')
const mongoose = require('mongoose')
const bodyparser = require('body-parser')
const FormRoute = require('./routes/FormRoute')
//database
mongoose.connect('mongodb://localhost:27017/form', { useNewUrlParser: true, useUnifiedTopology: true })
const db = mongoose.connection
db.on('error', (err) => {
console.log(err)
})
db.once('open', () => {
console.log("Database connection established!")
})
//app
const app = express()
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//cors
const cors = require('cors')
app.use(cors())
//server run
const PORT = process.env.PORT || 5000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
})
app.use('/api/form', FormRoute);
FormModel.js: (this is signup form model)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const formSchema = new Schema({
title: {
type: String
},
fname: {
type: String
},
lname: {
type: String
},
email: {
type: String
},
phoneNumber: {
type: String
},
cv: {
type: String
},
coverLetter: {
type: String
},
score: {
type: Number,
default: 0
}
}, { timestamps: true })
const form = mongoose.model('form', formSchema)
module.exports = form
FormXYZModel.js: (this is XYZ form model)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const formXYZSchema = new Schema({
name: {
type: String
},
email: {
type: String
},
password: {
type: String
},
dateOfBirth: {
type: Date
},
role: {
type: String,
default: user
}, { timestamps: true })
const formXYZ = mongoose.model('formXYZ', formSchema)
module.exports = formXYZ

My Post function not working with Postman heres in MonogDb

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.

How to fix post method error using ExpressJs and MongoDB

I'm new in Express.js,MongoDb and mongoose, I have created HTTP request methods, but when running the Post method, nothing is done (nothing saved in the database), and postman still loading and it stops only when I cancel. I want to know what's wrong in my code, thank you .
router.post("/v1/department", async (req, res) => {
try {
const request = req.body
const department = new Department(request)
await department.save()
res.status(200).send(department)
} catch (error) {
res.status(500).send(error)
}
});
This is my model
const mongoose = require("mongoose");
const validator = require('validator')
const Department = mongoose.model('Department', {
name: {
type: String,
required: true,
}
,
email: {
type: String,
required: true,
trim: true,//
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email!')
}
}
}
,
createdBy: {
type: String,
default: 'SYS_ADMIN'
}
,
updatedBy: {
type: String,
default: 'SYS_ADMIN'
}
,
createdAt: {
type: Date
// ,
// default: Date.getDate()
}
,
updatedAt: {
type: Date
// ,
// default: Date.getDate()
},
isDeleted: {
type: Boolean,
default: false
}
})
module.exports = Department
This is the Index.js
const express = require("express");
const app = express()
const departmentRouter = require("../src/routes/department")
app.use(express.json())
app.use(departmentRouter)
//app.use('/', require('./routes/department'))
const port = process.env.PORT || 5000;//local machine port 3000
app.listen(port, () => (`Server running on local machine port ${port} 🔥`));
The connection to the database is :
const mongoose = require("mongoose");
//Connect to the local mongoDB database for testing the API localy
mongoose.connect('mongodb://127.0.0.1:27017/openemp-api-department', {
useNewUrlParser: true,
useCreateIndex: true
})
You're missing a few things here. Mongoose is never set up in the index.js so there is no connection to the database. This should help you follow step by step
Also in your router you're sending department1 which is never assigned.
If the link doesn't work or you need more information let me know.
For the latest version of Express which is (Express v4.16.0 and higher)
Use this in your server.js file: ----->
const express = require('express');
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
// For Express version less than 4.16.0
// ------------------------------------
const bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
otherwise your post request will give you error(like not recognizing any names etc)
so make sure to use these according to to express version
index.js file
const mongoose = require("mongoose");
const express = require("express");
const router = express.Router();
const axios = require("axios");
mongoose.connect(
"YourMongoUri",
{
useNewUrlParser: true,
useUnifiedTopology: true,
}
);
const dataSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
});
const modelData = mongoose.model("modelData", dataSchema);
router.get("/", (req, res) => {
modelData.find((err, doc) => {
if (err) console.log(err.message);
else {
res.send(doc);
}
});
});
router.post("/", (req, res) => {
const user = new modelData({
name: req.body.name,
age: req.body.age,
});
user.save((err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
router.put("/:id", (req, res) => {
const user = modelData.findByIdAndUpdate(
req.params.id,
{
name: req.body.name,
age: req.body.age,
},
(err, doc) => {
if (err) return console.log(err);
res.send(doc);
}
);
});
router.delete("/:id", (req, res) => {
modelData.findByIdAndDelete(req.params.id, (err, doc) => {
if (err) return console.log(err);
res.send(doc);
});
});
module.exports = router;
server.js file
const express = require("express");
const myRouter = require("./index");
const app = express();
const port = 3000;
app.use(express.json());
app.use(
express.urlencoded({
extended: true,
})
);
s;
app.use("/myroute", myRouter);
app.listen(port, console.log("listening on port 3000"));

Hi, I am getting error while making a POST request

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 }))

SyntaxError: Unexpected token b in JSON at position 3

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.

Resources