簡體   English   中英

如何在 node.js 中使用 Javascript 獲取發布請求的時間

[英]How to get the time a post request was made using Javascript in node.js

我正在制作一個基本的博客應用程序(我是 Web 開發的新手,所以我出於學習原因構建它,所以沒有任何高級內容),並且當有人需要發布某些內容時,他們會轉到“/撰寫”路線。 當他們像這樣向服務器發布 POST 請求時,

app.post("/compose",function(req,res){
    const postTitle = req.body.postTitle;
    const postCategory = req.body.postCategory;
    const postBody = req.body.postBody;
    const authorName = req.body.authorName; 

    if (postCategory === "movies"){
        MoviePost.findOne({title: postTitle}, function(err, foundPost){
            if(!err){
                if (!foundPost){
                    const newPost = new MoviePost({
                        title: postTitle,
                        content: postBody,
                        category: postCategory,
                        author: authorName
                    });
                    newPost.save(function(err){
                        if(!err){
                            res.redirect("/");
                        }
                    });
                } else {
                    res.send("Post title already exists!Revisit the compose page to publish anything else.")
                }
            } else {
                console.log(err);
            }
        });
});

並且它現在工作正常(我也使用 Body-Parser。但我還需要知道發出請求的時間,以便我可以在博客文章中包含書面時間。我該如何實現它?

如果您使用的是mongoose ,您可以簡單地向您的架構添加一個額外的屬性:

const { Schema } = require("mongoose");

const MovieSchema = new Schema({
    title: String,
    content: String,
    category: String,
    author: String,
    date: { type: Date: default: () => new Date() }
});

這將在新文檔保存到數據庫時自動將日期添加到新文檔中,因此您不必手動執行此操作。

我想我想通了,我是這樣做的(我也更新了帖子架構。),

    const postCategory = req.body.postCategory;
    const postBody = req.body.postBody;
    const authorName = req.body.authorName;
    const addedDate = new Date();
    const addedTime = addedDate.toString();

    if (postCategory === "movies"){
        MoviePost.findOne({title: postTitle}, function(err, foundPost){
            if(!err){
                if (!foundPost){
                    const newPost = new MoviePost({
                        title: postTitle,
                        content: postBody,
                        category: postCategory,
                        author: authorName,
                        time : addedTime
                    });
                    newPost.save(function(err){
                        if(!err){
                            console.log(addedTime);
                            res.redirect("/");
                        }
                    });
                } else {
                    res.send("Post title already exists!Revisit the compose page to publish anything else.")
                }
            } else {
                console.log(err);
            }
        });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM