2017-04-07 77 views
1

請你能幫我,出於某種原因,我無法發佈,我得到一個「不能POST/API /創建」,並在檢查頁面時顯示404錯誤。不能POST使用快遞和身體分析器

這裏是我的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(「」),它將不會顯示ed,表明該函數甚至沒有被執行。

任何幫助將非常感激。

回答

1

您需要發佈到/ TODO/API /創建,根據您當前的路線處理:

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