Reputation: 88
I am trying to pass a string from the frontend into the backend, but I have hit a roadblock. I am using Node, Express, Body Parser, EJS, and PostgreSQL. My basic file system is this:
– app
|– api
| |– thing.js
|
|– index.js
– views
|– pages
|– index.ejs
I have a form submission in index.ejs that passes data to the index.js file:
index.ejs
<form action="/creatething" method="post">
<h1>Make a thing</h1>
<p> What is your thing called?
<input name="wtitle" type="text">
</p>
<p> What is your name?
<input name="cuser" type="text">
</p>
<input type="submit" value="Submit">
</form>
The above code triggers /creatething, which is placed in index.js
index.js
const express = require ('express');
const thingRouter = require('./api/thing');
const bodyParser = require("body-parser");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: false}));
app.use('/thing', thingRouter);
app.get('/', function (req, res){
res.render('pages/index');
});
app.post('/creatething',(req,res)=>{
console.log('clicked '+ req.body);
});
module.exports= app;
With this I am able to create a message in the console that prints the user input from the form. However, I am trying to send this data to a database through code in thing.js:
thing.js
const {Router} = require('express');
const router = new Router();
router.get('/',(req,res)=> {
console.log(req.body);
// Placeholder for working code that stores thing in database :)
});
module.exports = router;
The problem here is that I don't know how to pass the req.body data from the index.js file to the thing.js method that inserts the data into the database. I could just add the database code into the index.js file, but I was trying to keep things more separated and learn about routing/mounting. What am I missing at this point?
Upvotes: 3
Views: 956
Reputation: 5053
You have to change a few things in your thing.js
file. Only few lines of code is required instead of importing Router
from express and add some extra routes.
Just copy below code and paste to your respective files.
thing.js
const get = (req, res) => {
console.log(req.body);
}
module.exports = get;
index.js
const express = require ('express');
const get = require('./api/things');
const bodyParser = require("body-parser");
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({extended: false}));
app.get('/', function (req, res){
res.render('pages/index');
});
app.post('/creatething', (req,res)=>{
get(req,res);
});
app.listen(4000, () => {
console.log('App is running on port: 4000');
});
module.exports= app;
Hope this helps you solve the issue.
Upvotes: 1