【发布时间】:2020-10-05 09:52:51
【问题描述】:
我目前正在制作一个基本的 Twitter 克隆。在我提出发帖请求时,在我的文字开始没有出现之前,一切都很完美。 会有什么问题? 我的代码:
app.js:
var express = require("express"),
mongoose = require("mongoose"),
bodyParser = require("body-parser"),
ejs = require("ejs");
var app = express();
mongoose.connect("mongodb://localhost:27017/twitter_clone", {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => console.log("CONNECTED TO DB"))
.catch((error) => console.log(error.message));
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.static(__dirname + '/public'));
app.set("view engine", "ejs");
// MONGODB TWEETS SCHEMA
var tweetsSchema = new mongoose.Schema({
text: String
})
var Tweets = mongoose.model("Tweets", tweetsSchema);
//================
//RESTFUL ROUTES
//================
// INDEX ROUTES
app.get("/", function(req, res){
Tweets.find({}, function(err, allTweets){
if(err){
console.log(err);
} else {
res.render("home", {newtweet:allTweets});
}
})
})
app.get("/explore", function(req, res){
res.render("explore");
})
app.get("/notifications", function(req, res){
res.render("notifications");
})
app.get("/messages", function(req, res){
res.render("messages");
})
app.get("/bookmarks", function(req, res){
res.render("bookmarks");
})
app.get("/lists", function(req, res){
res.render("lists");
})
app.get("/profile", function(req, res){
res.render("profile");
})
app.get("/more", function(req, res){
res.render("more");
})
// NEW ROUTES
app.get("/tweet/new", function(req, res){
res.render("new");
})
// POST
app.post("/posttweet", function(req, res){
var text = req.body.text;
var newtweet = {text: text};
Tweets.create(newtweet, function(err, newTweet){
if(err){
console.log(err)
} else {
res.redirect("/");
}
})
})
//DELETE
app.get("/delete/:id", function(req,res){
mongoose.model("Tweets").remove({_id:req.params.id}, function(err, delData){
res.redirect("/");
})
})
app.listen(5000, function(){
console.log("Server listening on port 5000");
})
主页.ejs:
<form action="/tweet/new">
<input class="bluebutton" type="submit" value="Tweet" />
</form>
<div class="tweets">
<% newtweet.forEach(function(newtweet){ %>
<div class="showtweets">
<p class="tweetcontent">
<%= newtweet.text %>
</p>
</div>
<% }) %>
</div>
我之前问过一个类似的问题,我找到了一个解决方案,它运行了一段时间,但我做了一些改变,现在它不能正常工作。
【问题讨论】:
-
您在 home.ejs 的哪个位置发出 post 请求?表单使用 GET 方法向 /tweet/new 发送请求。
-
它的工作方式与 href="/tweet/new" 相同,只是指向表单页面的链接
标签: javascript node.js mongodb express mongoose