我有一个简单的RESTAPI crud应用程序,其中的帖子和评论应该提交到nodeJS路由。一切正常,因为它只说:单击表单按钮之一,在浏览器中永远“等待本地主机”。 这可能是由于html / ejs中的事件传播引起的吗?预先感谢!
app.js:
var methodOverride = require("method-override");
var express = require("express");
var express = require("express");
var bodyParser = require("body-parser");
var app = express();
app.use(methodOverride("_method"));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
let myDB = [{ post: "hello", comment: "hello1" }];
//Read
app.get("/", function(req, res) {
res.render("index.ejs", { posts: myDB });
});
//Create
app.post("/addPost", function(req, res) {
let newComment = { post: req.body.createP, comment: req.body.createC };
myDB.push(newComment);
});
//Update
app.put("/updatePost", function(req, res) {
let index = Number(req.body.updateI) - 1;
// res.send("you have reached the update route " + index);
let updatedComment = { post: req.body.updateP, comment: req.body.updateC };
myDB.splice(index, 0, updatedComment);
});
//Delete
app.delete("/deletePost", (req, res) => {
//res.send("you have reached the delete route " + req.body.del);
let index = Number(req.body.updateI) - 1;
myDB.splice(index, 1);
});
app.listen(3000, function() {
console.log("server is running");
});
index.ejs:
<h1>Index page</h1>
<P>Read posts</P>
<% posts.forEach(function(post){ %>
<li><%=post.post %></li>
<li><%=post.comment %></li>
<%})%>
<P>Create post</P>
<form action="/addPost" method="POST">
<input type="text" placeholder="post" name="createP" />
<input type="text" placeholder="comment" name="createC" />
<button>Create a new post</button>
</form>
<P>Update post</P>
<form action="/updatePost?_method=PUT" method="POST">
<input type="text" placeholder="ID" name="updateI" />
<input type="text" placeholder="post" name="updateP" />
<input type="text" placeholder="comment" name="updateC" />
<button>Create a new post</button>
</form>
<P>Delete post</P>
<form action="/deletePost?_method=DELETE" method="POST">
<input type="text" placeholder="sequence number" name="delI" />
<button>Delete a post</button>
</form>
<form action="http://localhost:3000/">
<input type="submit" value="Refresh" />
</form>
答案 0 :(得分:2)
我认为您是API开发的新手。执行某些数据库操作后,您没有将任何响应发送回浏览器。因此,浏览器等待响应直到请求超时。每次提交表单后,您都应该发送如下响应:
app.post("/addPost", function(req, res) {
// application logic goes here
// once done send response as below
res.render("index.ejs", { posts: updatedPosts });
})
另外,了解Ajax请求与表单操作submit