Contactで入力して、情報を送信し、Subscriberファイルで入力した情報を閲覧できるようにしたいのですが、情報が入ってません。どうしたら、新しい情報をセーブできるでしょうか。index.js, subscriberController.js, contact.ejs,subscriber.ejsのファイルを添付しました。
どうぞよろしくお願いいたします。
index.js
const express = require("express"), app = express(), mongoose = require("mongoose"), Subscriber = require("./models/subscriber"), subscribersController = require("./controllers/subscribersController"); mongoose.connect( "mongodb://localhost:27017/recipe_db", {useNewUrlParser: true} ); const db = mongoose.connection; db.once("open", () => { console.log("Successfully connected to MongoDB using Mongoose!"); }); var myQuery = Subscriber.findOne({ name: "Jon Wexler" }) .where("email", /wexler/); myQuery.exec((error, data) => { if(data) console.log(data.name); }); app.set("port", process.env.PORT || 3000); app.set("view engine", "ejs"); app.use(express.json()); app.get("/subscribers", subscribersController.getAllSubscribers, (req, res, next) => { res.render("subscribers", { subscribers: req.data}); }); app.get("/contact", subscribersController.getSubscriptionPage); app.post("/subscribe", subscribersController.saveSubscriber); app.listen(app.get("port"), () => { console.log(`Server running at http://localhost:${app.get("port")}` ); });
subscriberController.js
const { rawListeners } = require("../models/subscriber"); const Subscriber = require("../models/subscriber"); exports.getAllSubscribers = (req, res, next) => { Subscriber.find( {}, (error, subscribers) => { if(error) next(error); req.data = subscribers; next(); }); }; exports.getSubscriptionPage = (req, res) => { res.render("contact"); }; exports.saveSubscriber = (req, res) => { let newSubscriber = new Subscriber({ name: req.body.name, email: req.body.email, zipCode: req.body.zipCode, vip: req.body.vip }); newSubscriber.save((error, result) => { if (error) res.send(error); res.render("thanks"); }); };
subscriber.ejs
<div class="list-container"> <% subscribers.forEach(s => { %> <div class="subscriber"> <p> <span class="item-label">Name:</span> <%= s.name %> </p> <p> <span class="item-label">Email:</span> <%= s.email %> </p> <p> <span class="item-label">ZipCode:</span> <%= s.zipCode %> </p> <p> <span class="item-label">VIP:</span> <%= s.vip %></p> <% }); %> </div> </div>
contact.ejs
<div class="col-sm-6"> <img src="images/graph.png" alt=""> </div> <div class="col-sm-6"> <h1>Subscribe!</h1> <p>Enter your email if you're interested to learn more:</p> <form action="/subscribe" method="post"> <label for="name">Name</label> <input type="text" name="name" value=""> <br> <label for="email">Email</label> <input type="email" name="email" value=""> <br> <label for="zipCode">ZipCode</label> <input type="text" name="zipCode" value=""> <br> <label for="vip">VIP</label> <input type="text" name="vip" value=""> <br> <input type="submit" name="" value="Submit"> </form> </div>
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2021/04/02 06:30