0

So, I am using Node.js with express to run a server and make a calculator. After that, I downloaded body-parser, to get the access of the numbers the user inputs and use it to calculate the result, but for some reason whenever I try to log one of the numbers on console, just to make sure that it works, it doesn't get logged.

const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.get('/', (req, res) => {
  res.sendFile(`${__dirname}/index.html`);
})

app.post('/', (req, res) => {
  console.log(req.body);
  res.send('Thanks for the information');
})

app.listen(3000, () => console.log('Server Started'));

  • 1
    And how are you calling this route? Also you don't need body-parser any longer, [it's been deprecated](https://stackoverflow.com/questions/24330014/bodyparser-is-deprecated-express-4) long ago. – Jeremy Thille Sep 09 '20 at 13:27
  • So what should I use? I saw this code in a course. – MayBeNextT1me Sep 09 '20 at 13:29
  • Click on the link, you'll get the answer : `If you're using express > 4.16, you can use express.json()` – Jeremy Thille Sep 09 '20 at 13:32
  • hmm. Can you please share the code.. What should I write to get the access to those numbers and then add them up? – MayBeNextT1me Sep 09 '20 at 13:36
  • Again... click the link. It's discussing about body-parser being deprecated and what replaced it. You will find `app.use(express.json())`. But that's not a big deal, I guess it should work anyway. However, you haven't answered my question about how you call this toute – Jeremy Thille Sep 09 '20 at 13:41
  • I didn't really get your question? What do you mean by calling this route? As far as I know, I send my html file to my main route, i.e., '/ ' and then posted 'thanks for the information' to that same route (which gets rendered after the user hits submit button). – MayBeNextT1me Sep 09 '20 at 13:46
  • This route : `app.post('/'...)` How do you call it? You must call it somehow, if you expect a log to appear. What's the code that calls this route? – Jeremy Thille Sep 09 '20 at 13:48
  • Also, I don't think you need to manually send the `index.html` file. It's kind of Express's default behaviour on the `GET /` route. – Jeremy Thille Sep 09 '20 at 13:50
  • I don't know how to call it.. :( I saw this on the course and tried to implement it, but it didn't work. How do I call this route? – MayBeNextT1me Sep 09 '20 at 13:51
  • With an Ajax request, of course :) For instance with jQuery : `$.post("/", { foo : bar } )`. Since you don't know how to call the route, it makes sense that you get no `console.log(req.body)`... The server is listening, but nobody's calling this route, so its callback function doesn't get executed. – Jeremy Thille Sep 09 '20 at 13:55

1 Answers1

0

Your form will look something like this

<form id="post-form" action="/your/post/url" method="POST">
     <div class="form-control">
         <label for="title">Number</label>
         <input type="number" name="number" id="number">
     </div>

      <button type="submit">
         Submit
      </button>
</form>

Or in your script tag, you can do something like this. with this approach, the form gets submitted without reload

// Note: Optional approach (without reloading the page) 
// Just above HTML only code also works perfectly fine
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const number= document.getElementById('number')
document.getElementById('post-form').addEventListener('submit', (e) => {
    e.preventDefault();
    axios
        .post('/your/post/url', { number: number.value })
        .then((res) => {
            //handle response here
        })
        .catch((err) => { //handle err here});
});
<script>

then in you express app you can do

app.post('/you/post/url/', (req,res,next) => { 
   // this is how you accces title from you form
  // here title will hold value "Value Here"
  const { number} = req.body
  //calculate here
  number = number * number + number
  
  // then send the response 
  res.send(`calculated number: ${number}`)
});
Basanta Kc
  • 245
  • 4
  • 5