Ashish sah
Ashish sah

Reputation: 755

Not able to use post request in node js

<form class="ui form"  action"/submit" method="post">
        <div class="field">
            <label>Time you gave to your Studies:</label>
            <input type="number" name="study" placeholder="Total time given:">
        </div>
        <div class="field">
            <label>Time you gave to your <%= prof %> :</label>
            <input type="number" name="profession" placeholder="total time given for profession">
        </div>
        <div class="field">
            <label>Time you gave for Sleeping :</label>
            <input type="number" name="sleeping" placeholder="total time spent on Sleeping">
        </div>
        <div class="field">
            <label>Time you gave to your games :</label>
            <input type="number" name="games" placeholder="total time given for games">
        </div>
        <button class="ui button" type="submit">Submit</button>
</form>

This was my form and I am using Express. app.js is the main file and index.js contains routes in which I have few routes:

router.post('/submit', function(req, res, next) {
var item = {
    study: req.body.study,
    profession: req.body.profession,
    sleeping: req.body.sleeping,
    games: req.body.games
};
console.log(item);
res.render('/index');});

I am not able to post the form data whenever I click submit button it shows 404 error, What wrong I am doing? , How to make a post request and get the forum data?

Upvotes: 0

Views: 100

Answers (3)

Daksh
Daksh

Reputation: 986

From the code you've posted, it seems like you're using EJS templating engine. Here's how you should render an EJS, or in fact any templating engine file:

res.render('index');

This will render a file named index.ejs as HTML. If you're using another templating engine such as Pug, it would render a file named index.pug.


For future reference, here's the stuff you can send as response in Express:

  • Render a template file: res.render('index');
  • Send a file: For example, res.sendFile('index.html'); or res.sendFile('item.pdf');
  • Send some JSON data: res.json(myJsonObject);
  • Plain text: res.send('Hello World!');

The official Express docs are an excellent resource to learn more about Express.

Upvotes: 2

Aaron Raff
Aaron Raff

Reputation: 49

Also, if you are using res.render then you should be using a templating engine to render sent data. In this case it seems that you could just use res.sendFile. More info here.

Upvotes: 0

sidewinder
sidewinder

Reputation: 682

What you have:

 action"/submit" 

What you should have:

 action="/submit"

Upvotes: 2

Related Questions