【问题标题】:How to display an array of items using NodeJS?如何使用 NodeJS 显示项目数组?
【发布时间】:2022-01-22 06:07:38
【问题描述】:

我正在制作一个示例网页,以使用 NodeJS 显示数组中的书籍,但是当我运行代码时没有任何反应,只有一个空白页。我想要一个包含数组中书籍的页面。到目前为止我编写的代码如下,如果您能提供帮助,我会很高兴!

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

const app = express();
const port = 3000;

let books = [
    'book1',
    'book2'
];

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

app.use('/', express.static(__dirname));
app.get('/books', function(req, res) {
    res.render('index', {title: 'Books'});
});

app.post('/books', function(req, res) {
    const id = req.body.id;
    res.redirect('/books' + id)
});

app.listen(port);

【问题讨论】:

  • What Do You Mean “It Doesn’t Work”?edit您的问题并提供minimal reproducible example以及您的期望结果、您的实际结果,包括所有错误,并展示你的研究和你的尝试并解释究竟是什么没有奏效。
  • 那么到底是什么问题?
  • 问题是我运行代码时没有任何反应。期望的结果是数组中包含书籍的页面。
  • “什么都没有发生”到底是什么意思?
  • 那么浏览器会发生什么?你有超时错误吗?您是否检查过浏览器中的“网络”选项卡?

标签: javascript node.js express routes middleware


【解决方案1】:

如果您想要提供网页,您需要定义 html 页面的路径,例如:

app.use('/', express.static('public'))

在这里更好地解释How to make express serve static files from another upper directory?

为了使用 app.get,您需要对 localhost:3000/books 进行 GET 调用

与 app.post 相同,但执行 POST 请求。

【讨论】:

  • 问题是“显示数组中的书籍”——非常动态页面,而不是静态页面。
  • 是的,这是真的,很抱歉我错过了用户已经输入的 __dirname
猜你喜欢
  • 2020-07-09
  • 2023-01-19
  • 2020-02-27
  • 2020-11-09
  • 2012-03-21
  • 1970-01-01
  • 1970-01-01
  • 2021-07-30
  • 1970-01-01
相关资源
最近更新 更多