不能使用expression式和body-parser进行POST

请你能帮我一下,由于某种原因,我无法发布,并得到一个“不能POST / API /创build”,当检查页面404错误显示。

这是我的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 to use bodyParser for JSON and 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"); 

而相应的todoRoutes.js文件是我需要post方法的地方:

 var express = require('express'); var todoRoutes = express.Router(); var todoList = []; //to do 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 with 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 the following todo:", req.body.todo); todoList.push(req.body.todo); res.send({redirect: '/api/list'}); }); 

这里是相应的html文件:

 <!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 your new Todo:</label> <input type="text" id="todo" name="todo"> </div> <div class="button"> <button type="submit">Add</button> </div> </form> </body> </html> 

如果我在todoRoutes.js文件的POST函数中放置一个console.log(“”),它将不会被显示,表明该函数甚至不会被执行。

任何帮助将非常感激。

您需要根据您当前的路由处理POST到/ todo / api / create:

 <form action = "/todo/api/create" method="post">