不能使用express和body-parser进行POST

时间:2017-04-07 16:56:35

标签: node.js post

请你能帮助我吗,由于某些原因我无法发布并且收到“无法POST / api / create”,并且在检查页面时会显示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(“”),它将不会显示,表明该函数甚至没有被执行。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

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

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