2

I have set up a basic express server to accept some information submitted through a form. Unfortunately, I have run into some problems. I cannot log the data I receive onto the console. Can someone please help me figure this out?

app.js:

const express = require('express');
const path = require('path');

const app = express();
const port = 3000;

app.use(express.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname,'public')));

app.use('/',(req,res,next) => {
  res.sendFile(path.join(__dirname,'public','index.html'));
});

app.post('/api', (req, res) => {
  console.log(req);
})

app.listen(port, () => console.log(`App is listening on port ${port}!`))

And here's the form itself: index.html:

   <body>
      <h1>Hello there!</h1>
      <form id='form' method="POST" action="/api">
         <input id='textField' type='text' name='name' placeholder='Enter your name'>
         <p>Enter your date of birth:</p>
         <div class='dob'>
            <input id='date' type='number' name='date' placeholder='Date'>
            <select id='dobMonth' name="month">
               <option value="default">Month</option>
               <option value="Jan">January</option>
               <option value="Feb">February</option>
               <option value="Mar">March</option>
               <option value="April">April</option>
               <option value="May">May</option>
               <option value="June">June</option>
               <option value="July">July</option>
               <option value="Aug">August</option>
               <option value="Sept">Septmeber</option>
               <option value="Oct">October</option>
               <option value="Nov">November</option>
               <option value="Dec">December</option>
            </select>
            <input id='year' type='number' name='year' placeholder='Year'>
         </div>
         <input id='btn' type='submit'>
      </form>
      <script src='script.js'></script>
   </body>

Thanks in advance :)

2
  • Are you submitting the form normally or using AJAX? Commented Jan 14, 2020 at 18:57
  • The form is being submitted normally. I did try to use fetch API. But none of these worked successfully. Commented Jan 14, 2020 at 19:01

3 Answers 3

5

The problem is just the order of your routes. The first path you specify:

app.use('/',(req,res,next) => {
  res.sendFile(path.join(__dirname,'public','index.html'));
});

Is acting as a catch-all, since every path on the server includes '/'

If you switch the order and make the catch-all last, this should work just fine for you.

app.get('/api', (req, res) => {
  console.log(req);
})

app.use('/',(req,res,next) => {
  res.sendFile(path.join(__dirname,'public','index.html'));
});
Sign up to request clarification or add additional context in comments.

3 Comments

This solved the problem. Thank you very much. I also tried adding next() to the function, which also does the job. Not sure which one is the proper way.
What is the path value?
path in this snippet is a javascript library used for building file paths: nodejs.org/api/path.html Here it is used to join the environment variable __dirname with the directory public and filename index.html to make something like /Users/foo/src/myrepo/public/index.html
0

I think for this you need body-parser middleware and tnen you can get parsed data from request:

here is simple example:

var express = require('express')
var bodyParser = require('body-parser')

var app = express()

// create application/json parser
var jsonParser = bodyParser.json()

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: false })

// POST /login gets urlencoded bodies
app.post('/login', urlencodedParser, function (req, res) {
  res.send('welcome, ' + req.body.username)
})

// POST /api/users gets JSON bodies
app.post('/api/users', jsonParser, function (req, res) {
  // create user in req.body
})

But it's does not handle multipart bodies (post with files). Due to their complex and typically large nature. For multipart bodies, you may be interested in the following modules:

2 Comments

I don't think this is the problem because instead of using the bodyParser package from npm I'm using a similar middleware that comes out of the box express.js.
@DebabrataMondal, so first try with package, for example formidable and if work with package, then you can try parse raw request, just using only js. npmjs.com/package/formidable it's easy and fast package
0
<form class="innerWidth" action="/contact-detail/"  method="post">
   <label for="">Name</label>
   <input type="text" name="name">
   <label for="">Business Email</label>
   <input type="email" name="email"  >
   <label for="">Role</label>
   <input type="text" name="role">
   <label for="">Contact No.</label>
   <input class="contactInput"  type="text"  name="number" >
   <label for="">Message</label>
   <input class="messageInput" type="text"  name="message"  >
   <div class="submitBtn">
      <input  type="submit" value="Submit">
   </div>
</form>
app.post('/contact-detail/', jsonParser, function(req, res) {
    // create user in req.body
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.