node.js - Cannot POST using express and body-parser -
please can me out, reason not able post , getting "cannot post /api/create" , when inspecting page 404 error shown.
here index.js:
var express = require('express'); var app = express(); var bodyparser = require('body-parser'); var mainrouter = require('./mainrouter.js'); var todoroutes = require('./todoroutes.js'); //tell express use bodyparser json , url encoded form bodies app.use(bodyparser.json()); app.use(bodyparser.urlencoded({extended: false})); //mouting our routers app.use('/', mainrouter); app.use('/todo',todoroutes); app.listen(3000); console.log("express server running on port 3000");
and corresponding todoroutes.js file require post method:
var express = require('express'); var todoroutes = express.router(); var todolist = []; //to list array todoroutes.get('/', function(req, res) { res.sendfile(__dirname + '/views/todo/index.html'); }); todoroutes.get('/create', function(req, res) { res.sendfile(__dirname + '/views/todo/create.html'); }); todoroutes.get('/api/list', function(req, res) { res.json(todolist); //respond json }); todoroutes.get('/api/get/:id',function(req, res){ res.json(todolist[req.params.id]); }); todoroutes.post('/api/create', function(req, res){ console.log("creating following todo:", req.body.todo); todolist.push(req.body.todo); res.send({redirect: '/api/list'}); });
and here corresponding html file:
<!doctype html> <html lang = "en"> <head> <title>todo list: create</title> <meta charset="utf-8" /> </head> <body> <form action = "/api/create" method="post"> <div> <label for="todo">enter new todo:</label> <input type="text" id="todo" name="todo"> </div> <div class="button"> <button type="submit">add</button> </div> </form> </body> </html>
if put console.log("") in post function of todoroutes.js file not displayed, indicating function not executed.
any appreciated.
you need post /todo/api/create, based on current route handling:
<form action = "/todo/api/create" method="post">
Comments
Post a Comment