//This js file is the main running server
const express = require('express');
const ejs = require('ejs');
const app = express();
const bodyParser = require('body-parser');
//including middleware so we can use post requests
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
// Template engine for rendering is EJS
app.set('view engine', 'ejs');
//Specifies the directory of the static files to serve
app.use(express.static(__dirname + '/public/'));
//rendering the main home page
app.get('/',(req, res)=>{
res.render('index');
})
// not sure what to do here
app.post('/',(req, res)=>{
console.log(req.body);
});
//Opens a port to listen on
app.listen(3000,()=>{
console.log('Server is now running...')
});
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
// link to the databse connection
const URL = 'mongodb+srv://heyrio:<PASSWORD>@cluster0-7cpbz.mongodb.net/test?retryWrites=true';
// name of the collection
const database = 'Crud-Data';
// connects to the database
MongoClient.connect(URL, {useNewUrlParser: true}, (error, client)=>{
if(error){
return console.log('Could not connect to the database');
}
// creates a new collection
const db = client.db(database);
// adds a document to the designated collection
db.collection('User').insertOne({
// add user input here
});
});
note: I’ve just covered my password for this post in the URL string
the empty {} in the terminal is just from the console.log(req.body)
Thank you for your help I feel like I’m close
I’m still not getting how I can access the post data and pass it to the mongodb.js file I have so that I can pass the data into
db.collection('User').insertOne({
name: // I want the users data to go here
});
once I do access the post data can I just store it into a variable and just modules.export
I saw before which line printed the empty object, but I’m not sure which part caused it to be empty, so it’d be helpful to use the chrome network inspector to view what data was actually POSTed to the app
After you have the data in your express app, define an exported function in your mongodb.js and require and call it in the express app imo