I am having problems trying to connect variables from a browser based game to store in my mongoDB database.
Basically this is a condensed example as there will be numerous additional variables I will track and save, but in the example below I want the "round" to increment on button click. On the button click, I want the round number to be saved to a mongoDB database.
index.ejs file:
<h1>Round <span id="round">1</span></h1>
<form action="/" method="POST">
<button id="endbutton" type="submit">End Turn</button>
</form>
<script src="../scripts/game.js"></script>
game.js file:
let round = 1;
function endTurn(){
round += 1;
document.querySelector("#round").innerHTML = round;
}
let endTurnButton = document.querySelector("#endbutton");
endTurnButton.addEventListener("Click", endTurn);
module.exports = {round, endTurn};
app.js file:
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const path = require('path');
const gameJS = require('./scripts/game');
mongoose.connect("mongodb://localhost/variableTest", {useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false})
.then(() => {
console.log("Mongo connection open");
})
.catch(err => {
console.log("Mongo connection error occurred:")
console.log(err)
})
app.use(express.static(__dirname + "/public"));
app.use(bodyParser.urlencoded({extended: true}));
app.set('views', path.join(__dirname, 'views'));
app.set("view engine", "ejs");
const { Schema } = mongoose;
const gameSchema = new Schema({
date: Date,
round: Number,
});
const Game = mongoose.model("Game", gameSchema);
//=================
//ROUTES
//=================
app.get("/", async(req, res) =>{
res.render("index");
});
app.post('/', async(req, res) => {
const game = new Game({
date: Date.now(),
round: gameJS.round,
});
await game.save();
})
//=================
//SERVER
//=================
app.listen(3000, () => {
console.log("VariableTest server has started.");
})
Related
I am created a nodejs project the structure of py project is:
api.js is:
const express = require('express');
const router = express.Router();
const add = require('../model/myModel');
router.get('/',function(req,res){
res.render('myForm');
});
router.post('/add', (req, res) => {
console.log(req.body)
n = req.body.name,
phone = req.body.phone,
console.log(`name = ${n}`)
let obj = new Address({
name: n,
phone: phone,
});
// add this instance to the database.
obj.save()
.then((address) => {
res.send(address);
})
.catch((err) => {
console.log(error);
});
});
module.exports = router;
and my app.js is:
const express = require('express');
const mongoose = require('mongoose');
const route = require('./route/api');
//Initialize express app
const app = express();
// Connecting to DB
const dbPath = 'mongodb://localhost:27017/testdb';
const dbOptions = {useNewUrlParser: true};
mongoose.connect(dbPath, dbOptions).then(()=>{
console.log(`We are connected to our database ${dbPath}`);
}).catch((error)=>{
console.log(`We are note able to connect to our database: ${error}`);
});
app.use(express.static('public'));
app.use(express.json());
app.set("view engine", "ejs");
// initialize routes
app.use("/api", route);
//Initialize the sever
app.listen(3000, () => {
console.log('sever listening on port:3000');
});
and myForm.ejs is:
So, I want to be able to enter the data in myForm.ejs and save this data in the database. But when I fill the form and press submit my req.Body is an empty object. Where is my error?
Server side you need additional parser middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true })); //add this line
Client side your form should use /api/add, and not /add
I am testing a user registration route but its returning a Cannot POST /api/user and it seems i can't pin point the problems.
when I run a get request using postman, it works...but when I post, it returns a Cannot POST /api/user result .
Any sort of help/response will be greatly appreciated.
here is my server.js file.
const express = require('express');
const mongosse = require('mongoose');
const bodyParser = require('body-parser');
//const entries = require('./routes/api/entries');
const app = express();
const path = require("path")
//app.use(bodyParser.json());
app.use(express.json())
//const db = require('./config/keys.js').mongoURI;
mongosse
.connect('mongodb+srv://user:pass2i8y7#gytay.qpgpm.mongodb.net/myFirstDatabase?retryWrites=true&w=majority',
{
useUnifiedTopology: true,
useNewUrlParser: true,
useCreateIndex:true
})
.then(() => console.log('its connected'))
.catch(err => console.log(err));
app.use('/api/entries', require('./routes/api/entries'));
app.use('/api/user', require('./routes/api/user'));
//serve a static dish of data
if (process.env.NODE_ENV == 'production') {
//set static folder
app.use(express.static('client/build'));
app.get('*', (req, res) => {
res.sendFile(path.resolve(__dirname,
'client', 'build', 'index.html'));
});
}
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
And here is my User route.
const express = require('express');
const router__ = express.Router();
//User model
const User = require('../../models/User');
//#Post api/users
//#desc register user/s
router__.post('/', (req, res) => {
res.send('regesiter__here');
});
module.exports = router__;
I couldn't find any problem with the code so, i ended up restarting the server and it worked! everything good
I am trying to make my backend work with MongoDB ATLAS.
I'm using express, mongoose and node.js for my tests and when I am trying to test my API routes (in this case to add a user)
The code I have is the following:
users.js
const router = require('express').Router();
const { Router } = require('express');
let User = require('../models/user.model');
router.route('/').get((req, res) => {
User.find()
.then(users => res.json(users))
.catch(err => res.status(400).json('Error: ' + err));
});
router.route('/add').post((req, res) => {
const username = req.body.username;
const newUser = new User({username});
newUser.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router
user.model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
trim: true,
minlength: 3
},
}, {
timestamps: true,
});
const User = mongoose.model('User', userSchema);
module.exports = User;
server.js
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
require('dotenv').config();
const app = express();
const port = process.env.PORT || 5000;
app.use(cors());
app.use(express.json());
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, { useNewUrlParser: true, useCreateIndex: true }
);
const connection = mongoose.connection;
connection.once('open', () => {
console.log("MongoDB database connection established successfully");
})
const exercisesRouter = require('./routes/exercises');
const usersRouter = require('./routes/users');
app.use('/exercises', exercisesRouter);
app.use('/users', usersRouter);
app.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
When I am testing this with postman via a POST I get the following error: I am getting the following error: TypeError: User is not a constructor
The post is done to http over port 5000 with raw json body as "username": "blahblahblah"
Can you help with this maybe?
I am not sure what happened but today I cut and pasted back all the code and the API started to work just fine. Now I can add users without any problems.
Could be a glitch but not sure at this point.
This is my first day in express. I was trying to create a simple route but my save function doesn't seem to work. I tried looking at similar questions posted on stackoverflow but couldn't make it. Any help will be appreciated.
const express = require("express");
const router = express.Router();
const Post = require("../models/Post");
//ROUTES
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
description: req.body.description
})
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json(err);
});
});
module.exports = router;
And here is my model.
const mongoose = require("mongoose");
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
}
});
module.exports = mongoose.model('Posts',PostSchema);
app.js code
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");
//IMPORT ROUTES
const postsRoute = require("./routes/posts");
//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
app.use('/posts', postsRoute)
//app.use('/users', usersRoute)
//ROUTES
app.get('/', (req, res) => {
res.send("We are on home");
});
//CONNECT TO DB
mongoose.connect(
process.env.DB_CONNECTION,
{ useNewUrlParser: true },
() => {
console.log("DB Connected!!")
})
//How do we start listening to the server
app.listen(3000);
My postman query -
Postman Response -
Please let me know if you need any more information.
your app.js should be :
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
require("dotenv/config");
//MIDDLEWARE - Function that always execute when routes are being hit.
app.use(bodyParser.json())
mongoose.connect(process.env.DB_CONNECTION, { useNewUrlParser: true }, function(err) {
if (err) {
console.error('System could not connect to mongo server')
console.log(err)
process.exit()
} else {
console.log('System connected to mongo server')
}
});
//ROUTES
app.get('/', (req, res) => {
res.send("We are on home");
});
//IMPORT ROUTES
const postsRoute = require("./routes/posts");
app.use('/posts', postsRoute)
app.listen(3000);
also add console log in router to check req.body :
router.post('/', (req, res) => {
console.log('req.body===',req.body);
...
});
I'm trying to add book to MongoDB and try to post with Postman it just saves _id and _v. I read a lot of answers here but neither was helpful. Get books works good but I inserted a book from command prompt.
Is there any other method to save it ?
Here is the code of api.js file:
onst express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
var Book = require('../models/book');
//MONGODB CONNECTION
mongoose.connect('mongodb://127.0.0.1:27017/books' ,({useMongoClient: true}));
mongoose.connection.on('connected', () => {
console.log('Successfully connected to MongoDB');
});
mongoose.connection.once('error', (err) =>{
console.log('Error: '+ err);
});
//Get books
router.get('/books', function(req, res) {
Book.find(function(err, books) {
if (err) {
res.send(err);
} else
res.json(books);
});
});
//Post books
router.post('/books', (req,res) => {
let newBook = new Book (req.body);
newBook.name = req.body.name,
newBook.author = req.body.author,
newBook.pages = req.body.pages,
newBook.save((err, newBook) => {
if (err){
console.log(err);
} else {
res.json(newBook);
}
});
});
module.exports = router;
Here is the code of the model file:
const mongoose = require('mongoose');
var schema = mongoose.Schema;
var bookSchema = new schema ({
name: String,
author: String,
pages: Number
});
module.exports = mongoose.model('book', bookSchema, 'books');
And code of the server file:
const express = require('express');
const path = require('path');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const api = require('./server/routes/api');
const app = express();
//SERVER
const port = 3000;
app.listen(3000, () => {
console.log('Server started on port '+port)
});
// BODYPARSER
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
//API
app.use('/api', api);
// ROUTES
app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist/index.html'));
});