Node.js代码不按预期工作,并在数组中推两次对象?

blmhpbnm  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(88)

我正试图使一个博客网站和app.post("/compose", function() {})行,当我把包含数据的对象的用户到数组中,即职位定义的全球和每当我console.log数组我得到数组的输出两次,而不是一次。我该怎么纠正呢?
//jshint esversion:6

const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');

const homeStartingContent = 'Lacus vel facilisis ...';

const aboutContent = 'Hac habitasse platea dictumst ...';

const contactContent = 'Scelerisque eleifend donec pretium...';

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));

let posts = [];

app.get('/', function (req, res) {
    res.render('home', {
        homePageContent: homeStartingContent,
        listContent: posts,
    });
});

app.get('/about', function (req, res) {
    res.render('about', { aboutPageContent: aboutContent });
});

app.get('/contact', function (req, res) {
    res.render('contact', { contactPageContent: aboutContent });
});

app.get('/compose', function (req, res) {
    res.render('compose');
});

app.post('/compose', function (req, res) {
    let post = {
        newTitle: req.body.postTitle,
        newContent: req.body.blogContent,
    };

    posts.push(post);

    res.redirect('/');
});

app.listen(3000, function () {
    console.log('Server started on port 3000');
});

预期输出:output containing 1 array for 1 entry by user
错误输出:output containing 2 arrays for 1 entry by user

bjp0bcyl

bjp0bcyl1#

一切看起来都很好,但尝试添加在数组中使用扩展运算符

posts = [...posts,post]

或者你可以多尝试一种方式

posts[posts.length]=post

相关问题