简体   繁体   中英

Cannot read property 'date' of undefined in node.js

I have recently started using node.js and while using body parser I stumbled upon an error which i have no clue about. I get an error cannot read property 'date' of undefined although i am mentioning date in my html part.

my codes are as follows: app.js:

var moment = require('moment');
var express = require('express');
var bodyparser = require('body-parser');

var app = express();

app.set('view engine','ejs');

app.get('/',function(req,res){
    res.render('index');
})

app.get('/ans', function(req,res){
    res.render('ans');
})

app.post('/', function(req,res){
    var date = req.body.date;
    console.log(date);
    res.render('ans',{"date": date});
});

app.listen(3000,function(err){
    if(err) console.log(err);
    else
    console.log("App is running");
});

index.ejs:

<!DOCTYPE html>
<html>
    <head>
        <title>timestamp</title>
    </head>
    <body>
        <h1>API Basejump: Timestamp microservice</h1>
        <h2>Enter the date</h2>
        <form action="/" method="post" >
            <input type="text" name="date">
            <input type="submit">
        </form>
    </body>
</html>

ans.ejs:

<!DOCTYPE html>
<html>
    <head>
        <title>timestamp</title>
    </head>
    <body>
        <h1>API Basejump: Timestamp microservice</h1>
        <p>Date: <% date %></p>
    </body>
</html>

You need to setup express to use body-parser

var app = express();
app.use(bodyParser.urlencoded({ extended: false }))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM