I have a mongo model like this:-
var mongoose = require('mongoose');
const itemsModel = new mongoose.Schema({
_id: {
type: String,
},
userName: {
type: String,
required: true
},
description: {
type: String,
required: false
},
itemId: {
type: String,
required: true,
unique: true
}
});
module.exports = mongoose.model("itemsModel", itemsModel);
and I am handling my backend route in a file called itemRoute.js like this:-
const express = require("express");
const router = express.Router();
const id = require('uuid');
const itemsModel = require("../src/model/itemsModel");
router.post('/add-item/', (req, res) => {
const { userName, description, itemId } = req.body;
itemsModel.findOne({
itemId: itemId,
userName: userName,
}, (error, prevData) => {
if(error){
return res.send({
success: false,
description: `Internal Server Error ${error}`
});
}
if (prevData.length > 0){
itemsModel.findOneAndUpdate(
{ _id: prevData[0]._id },
{ description: description },
(error, status) => {
if (error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
} else {
return res.status(200).json({
success: true,
description: "Updated item successfully",
prevData: prevData,
status: status
});
}
}
);
}
const newModel = new itemsModel;
newModel._id = id.v4();
newModel.userName = userName;
newModel.itemId = itemId;
newModel.description = description;
newModel.save((error, user) => {
if(error){
return res.json({
success: false,
description: `Internal Server Error ${error}`
});
}
return res.status(200).json({
success: true,
description: "Added item to db",
user: user
});
});
});
});
router.get('/get-items/:itemId/', (req, res) => {
console.log(req.body);
const itemId = req.params.itemId;
return res.status(200).json({
success: true,
description: "Nicee",
id: itemId,
});
});
module.exports = router;```
I have the following in my index.js express file:-
app.use('/api', require('./routes/itemRoute'));
and I am calling from my frontend like this:-
handleAddItemButton = (event) => {
event.preventDefault();
const data = {
userName: this.props.userName,
description: this.state.description,
itemId: this.props.itemId,
}
fetch(`http://localhost:8000/api/add-item/`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data)
})
.then(res => res.json())
.then(res => {
console.log(res);
})
.catch((err) => console.log(err));
};
My index.js file:-
/* jshint esversion:6 */
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const mongoose = require('mongoose');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(express.static('./build'));
app.use(express.static('./build/static'));
app.use('/api', require('./routes/auth'));
app.use('/api', require('./routes/items'));
app.use('/api', require('./routes/itemRoute'));
mongoose.set('useCreateIndex', true);
const port = 8000
mongoose.connect('mongodb://localhost:27017/item-app', {
useNewUrlParser: true
})
app.get('/*', (req, res) => {
res.sendFile(path.resolve('./build/index.html'))
})
app.listen(port, () => console.log(`server running at ${port}`));
When my frontend actually makes the request, I am thrown the following error:-
POST http://localhost:8000/api/add-item/ net::ERR_CONNECTION_REFUSED
I have looked through my code again and again but to no avail. Any and all help is sincerely appreciated. Please guide me through what Im doing wrong.
Edit 1:-
After #ewokx comment I ran mongod and got the following;-
Is this the issue? How to solve this?
MongoDB requires a data folder to store its files.
The default location for the MongoDB data directory is c:\data\db. So, create this folder it will solve your issue.
Hi so I seem to have successfully solved the problem. The problem wasn't with any of the things like db permissions, mongod, ports or something like that. I reset my index.js file to match the db name in the db connection.
Another thing I was doing wrong, I was passing a json stringified object as the request body. Removing that and on connecting proeprly to the db, the code started working nicely.
Related
React beginner here and I am using axios to send the body from my form in my frontend. I did a console.log on the server side and this is what I see in the request.body.
req.body {
'{"body":"{\\"firstName\\":\\"daf\\",\\"lastName\\":\\"afa\\",\\"address\\":\\"af\\",\\"phoneNumber\\":\\"123-933-6177\\",\\"email\\":\\"asfa\\",\\"facilityName\\":\\"afs\\",\\"isSeller\\":false}"}': ''
}
class where I print the bad String above
checkIfDuplicateEmailAndFacilityNameOnSignUp = (req, res, next) => {
// get the customer name
console.log("request", req.body.firstName);
const updatedBody = JSON.parse(req.body);
console.log(updatedBody);
Customer.findOne({
where: {
email: req.body.email
}
}).then(customerEmail => {
if (customerEmail) {
res.status(400).send({
message: "This email is already in use"
});
return;
}
Customer.findOne({
where: {
facilityName: req.body.facilityName
}
}).then(facilityname => {
if (facilityname) {
res.status(400).send({
message: "Facility exists already exists"
});
return;
}
next();
});
});
};
This is my function to post from the front end
const onFormSubmit = (event) => {
event.preventDefault();
const formBody = {
...this.state,
};
axios({
method: "POST",
url: "http://localhost:3000/api/auth/signup",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
data: {
body: formBody,
},
}).then((response) => {
console.log("response", response);
console.log("response data", response.data);
});
console.log("form submission done");
};
state object
state = {
firstName: "",
lastName: "",
address: "",
phoneNumber: "",
email: "",
facilityName: "",
isSeller: false,
};
this is my node server.js file
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(bodyParser.json());
app.use(
cors({
origin: "*",
})
);
app.use(
bodyParser.urlencoded({
extended: true,
})
);
require('./app/routes/authRoutes')(app);
require('./app/routes/customerRoutes')(app);
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Now listening on port ${PORT}`);
});
db.sequelize.sync({
force: true
})
.then(() => {
console.log("Dropping and Resync DB");
initial();
});
// creates roles in database for us
function initial() {
Role.create({
id: 1,
roleType: "buyer"
});
Role.create({
id: 2,
roleType: "seller"
});
};
I tried using JSON.parse() but I get an exception with the message Unexpected token o in JSON at position 1. Any idea on how I can go about parsing this?
Update 1:
After changing per #Bravo answer the body looks like this now
body: {
firstName: 'safds',
lastName: 'asf',
address: 'adfs',
phoneNumber: '404-932-6177',
email: 'asdf',
facilityName: 'afs',
isSeller: false
}
Might be a silly question but how do I access the fields. I tried doing body.firstName or body[0] but I get undefined returned?
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
This is the problem. You're lying about the encoding so Express is running your body through bodyParser.urlencoded instead of bodyParser.json.
Take the custom headers out and just use Axios' defaults.
I have recently started using node.js as my backend and I have successfully posted data to the database, the problem that I am facing now is telling the front end that data has been successfully saved. Below is my user route with all the things I have tried commented out.
import { Router } from 'express';
import { IUser } from '../models/user.model';
const User = require('../models/user.model');
// import bcrypt from 'bcrypt';
const bcrypt = require('bcrypt');
const bodyParser = require('body-parser');
// create application/json parser
var jsonParser = bodyParser.json()
// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })
const userRouter = Router();
userRouter.get('/', (req, res) => {
return res.json('This is the user route');
})
userRouter.post("/register", (req, res: any, next) => {
const user: IUser = new User({
email: res.email,
firstName: res.firstName,
lastName: res.lastName,
password: res.password,
displayName: res.displayName,
cellNumber: res.cellNumber,
});
user.save()
.then((result: any) => {
res.status(201).json({
message: 'Successfully created a new user!',
result: result
});
// res.sendCode(201);
// console.log(res);
// res.status(201).send("User has been successfully created");
//return 'User has been successfully created';
// return Object({ message: "User has been successfully created" });
// return res.status(201).send({
// message: "User has been successfully created",
// statusCode: 201
// })
// return res;
})
.catch((err: any) => {
res.status(500).json({
error: err
})
})
// bcrypt.hash(req.body.password, 10)
// .then((hash: string) => {
// const user = new User({
// email: req.body.email,
// firstName: req.body.firstName,
// lastName: req.body.lastName,
// password: hash,
// displayName: req.body.displayName,
// cellNumber: req.body.cellNumber,
// });
// user.save()
// .then((res: any) => {
// res.status(201).json({
// message: 'Successfully created a new user!',
// result: res
// });
// })
// .catch((err: any) => {
// debugger;
// res.status(500).json({
// error: Error
// })
// })
// })
})
export default userRouter;
which I then export to the server.ts file which is below
import express = require('express');
//import cors from 'cors';
const cors = require('cors');
const bodyParser = require('body-parser')
import { Router } from 'express';
import mongoose from "mongoose";
import "dotenv/config"
//routes
import userRouter from './routes/user.routes';
//Create a new express instance
const app: express.Application = express();
app.get('/', function (req, res) {
res.send('Hello World');
});
// //get router
// var router = express.Router();
//Database
mongoose.connect(`${process.env.MONGO_URI}`,
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
})
.then(() => {
console.log("Connected to MongoDB")
})
.catch(() => {
console.log("Connection to Database has failed")
})
var corsOptions = {
origin: '*',
credentials: true,
methods: '*'
};
const routes = Router();
export default routes;
app.use(routes);
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cors(corsOptions));
app.use("/user", userRouter);
routes.use('/user', userRouter);
routes.use(cors(corsOptions));
//use cors middleware
// router.use(cors(options));
app.listen(3000, function () {
console.log('App is listening on port 3000!');
})
What is strange is that when I set breakpoints and analyse the res file, i can see the data that I would have posted from the front end. But the front end gets the 500 status code instead of the 201 that I want to be sending, even though it passes right over that code. I have googled the keys of my keyboard for three days now. So I am at a loss now.
All The latest changes can be found in the GitLab repository below
https://gitlab.com/ShanahJr/SuperiorBallers
You just need to make use of res variable provided by express.
Example -
module.exports.updateData = async (req, res, next) => {
try {
const data = await Editor.edit(req.body.query);
res.status(200).json({ "status": true, "result": 'Edit successful!' })
} catch (error) {
console.log(error)
res.status(200).json({ "status": false, "result": "Request Failed!" })
}
}
This statement - res.status(200).json({ "status": true, "result": 'Edit successful!' })
Nowadays, express also suggests using res.sendStatus(200) over res.status(200)
You can lookup for status codes here
Use res.status(201).send(), res.status().json usually gets blocked by http rules especially when you activate https
I am trying to create a sample API of restaurants using POST but after starting API and loading it into Postman it does not show results.
router.js
const express = require('express');
const restaurantController = require('../Controllers/restaurantData');
const router = express.Router();
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
module.exports = router;
app.js
const express = require('express');
const bodyparser = require('body-parser');
const mongoose = require('mongoose');
const apiRouter = require('./Routes/router');
const port = 4005;
const app = express();
app.use(bodyparser.json());
app.use('/api', apiRouter);
mongoose.connect(
'mongodb://127.0.0.1:27017/sample',
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(success => {
console.log('Connected to MongoDB');
app.listen(port, () => {
console.log(`Server started at port ${port}`);
});
}).catch(error => {
console.log(error);
});
restaurant.js (Controller)
const restaurants = require('../Models/restaurantData');
exports.getfilter = (req, res) => {
const city_name = req.body.city_name;
const cost = req.body.cost;
restaurants.find({
city_name: city_name,
cost: cost
}).then(result => {
res.status(200).json({
message: "Filtered Data",
result
})
}).catch(error => {
res.status(500).json({
message: error
})
})
}
restaurantData.js (Model)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const restaurantSchema = new Schema({
name: {
type: String,
required: true
},
city_name:{
type: String,
required: true
},
city: {
type: Number,
required: true
},
area: {
type: Number,
required: true
},
locality:{
type: String,
required: true
},
thumb: {
type: String,
required: true
},
cost:{
type: Number,
required: true
},
address:{
type: String,
required: true
},
mealtype:{
type: Number,
required: true
},
name:{
type: String,
required: true
},
cuisine:{
type: Number,
required: true
},
type:{
type: Array,
required: true
},
Cuisine:{
type: Array,
required: true
}
});
module.exports = mongoose.model('restaurantData', restaurantSchema, 'restaurantData');
I think mostly it is the router problem but trying to know where? So, share any ideas. Thank You.
This request handler:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter
});
Does not actually call the getfilter function so nothing is ever sent from the POST request. You can fix that by either doing this:
router.post('/restaurantFilter', restaurantController.getfilter);
or this:
router.post('/restaurantFilter',(req, res) => {
restaurantController.getfilter(req, res);
});
Then, it looks like you also have to property export and import that getfilter() function. You appear to export it just fine in restaurant.js:
exports.getfilter = (req, res) => { ... });
But, you don't seem to be importing the controller properly as you're doing this:
const restaurantController = require('../Controllers/restaurantData');
When it looks like you should be doing this:
const restaurantController = require('../Controllers/restaurant.js');
so that you're assigning the controller the object that actually has the getfilter method on it.
i'm new to nodejs, i'm using express-session for my project
I can't retrieve session values nowhere than my login route
I see many people have the same problems
Any recommend or help would be awesome ! you all have a nice day !
Here's my login route
route.post('/verify', (req, res) => {
const email = req.body.email;
const pass = req.body.password;
userModel.findOne({ email: email }, (err, data) => {
if (err) {
console.log(err);
res.status(500).json({
success: false,
message: error.message
});
}
else {
if (data !== null) {
if (!bcryptjs.compareSync(pass, data.password)
) {
res.status(400).json({
success: false,
message: "Wrong Password"
})
}
else {
req.session.currentUser = {
email: data.email,
};
console.log(req.session);
res.status(200).json({
success: true,
message: "Login Success",
data: {
email: data.email,
name: data.name,
id:data.id,
}
})
}
}
else {
res.status(404).json({
success: false,
message: "Email doesn't exist"
})
}
}
})
})
Here's my server.js setup:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
const session = require('express-session');
const bcryptjs = require('bcryptjs');
const passport = require('passport');
var Schema = mongoose.Schema;
require('./passport/facebook-auth')(passport);
require('dotenv').config();
const passportSetup = require('./passport/google-auth');
const authRoutes = require('./routes/auth-routes');
const userRoutes = require('./user/user.routes')
const userModel = require('./user/user.schema');
// connect to mongodb
mongoose.connect('mongodb://' + process.env.USER + ':' + process.env.PASS + '#localhost:27017/' + process.env.DATABASE + '?authSource=admin', { useNewUrlParser: true, useUnifiedTopology: true }, (e) => {
//FIXME: tim cach viet khac
if (e)
throw e;
else {
console.log("MongoDB Connected...");
// basic init
const server = express();
server.use(session({
secret: 'keyboard cat',
resave: true,
saveUninitialized: false,
}));
server.use(express.static('public'));
// set up cors to allow us to accept requests from our client
server.use(cors({
origin: "http://localhost:3000", // allow to server to accept request from different origin
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true // allow session cookie from browser to pass through
})
);
server.use(bodyParser.json());
// set up session cookies
// initialize passport
server.use(passport.initialize());
server.use(passport.session());
// set up route
server.use('/auth', authRoutes);
server.use('/users', userRoutes);
server.listen(process.env.PORT || 5000, (err) => {
if (err)
throw err;
else
console.log("Server listening on port 5000...");
console.log('hadm x tanhng...');
console.log('ununneee here we come');
});
}
})
after logging in , the session is destroyed automatically
thank you once again
Here is my code:
//server.js
const express = require('express'),
cors = require('cors'),
bodyParser = require('body-parser'),
mongoose = require('mongoose');
const Mate = require('./models/mate');
mongoose.Promise = global.Promise;
const app = express();
const router = express.Router();
app.use(cors());
app.use(bodyParser.json())
mongoose.connect('mongodb://localhost:27018/mate', {useNewUrlParser: true});
const connection = mongoose.connection;
connection.once('open', () => {
console.log('Mongodb db connection established succ');
})
router.route('/mate').get((req, res) => {
mongoose.model('Mate').find((err, mate) => {
if (err)
console.log(err);
else
res.json(mate);
});
});
router.route('/mate/:id').get((req, res) => {
mongoose.model('Mate').findById((err, mate) => {
if(err)
console.log(err);
else
res.json(mate);
});
});
router.route('/mate/add').post(async (req, res) => {
try {
const mate = new Mate(req.body);
await mate.save();
res.status(200).json({
'mate:': 'Added succesfully'
});
} catch (err) {
console.log(err);
res.status(400).send( 'failed to create' );
}
});
router.route('mate/update/:id').post((req, res) => {
mongoose.model(Mate).findById(req.params.id, (err, mate) =>{
if(!mate)
return next(new Error('couldnt load doc'))
else {
mate.title = req.body.title;
mate.day = req.body.day;
mate.severity = req.body.severity;
mate.status = req.body.status;
mate.save().then(mate => {
res.json('Update done');
}).catch(err => {
res.status(400).send('update failed');
});
}
});
});
router.route('mate/delete/:id').get((req, res) => {
mongoose.model(Mate).findByIdAndRemove({_id: req.params.id}, (err, mate) => {
if(err)
res.json(err);
else
res.json('Removed');
});
});
app.use('/', router);
app.listen(4000, () => console.log('server running on port 4000'));
//mate.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema;
let MateSchema = new Schema({
title: {
type: String
},
day: {
type: String
},
severity: {
type: String
},
status: {
type: String,
default: 'Open'
}
});
module.export = mongoose.model('Mate', MateSchema);
So basically problem is with add controller in server.js, that must throw post request to my DB with new json created.
Well, it doesn't, but it throws this error:TypeError: Mate is not a constructor;
Help me please figure out why is it going so. I'm new at code so this may be silly question, but i'm stuck at it.
make mate.js like below
module.exports = function(mongoose) {
var options = {
collection: 'mate',
timestamps: {
createdAt: 'created_on',
updatedAt: 'updated_on'
},
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
};
let MateSchema = new mongoose.Schema({
title: {
type: String
},
day: {
type: String
},
severity: {
type: String
},
status: {
type: String,
default: 'Open'
}
});
return MateSchema;
};
Make changes in the module export as:
module.export = Mate = mongoose.model('Mate', MateSchema);