【问题标题】:Why I don't get the data when going on the route?为什么我在路上时没有得到数据?
【发布时间】:2018-11-12 14:50:37
【问题描述】:

当我去路由'/gallery' 时,我想从文件“posts.json”接收数据。 我使用fs 模块从文件中获取数据,并使用read() 方法从文件“posts.json”中读取数据。

因此,我收到错误:'ReferenceError: fs is not defined'

当使用fs 模块在路由'/gallery' 中导航时,如何从文件“posts.json”中显示数据?

app.js:

const express = require('express');
const  Database =  require('./db');

const app = express();
const port = 3000;
const  db = new Database();

app.use(express.json());

app.get('/gallery', (req, res) => {
    const items = db.read();
    res.send(items);
});

app.listen(port, () => {
    console.log(`Example app listening on port ${port}!`);
});

db.js:

class Database {

    constructor(){
        this.fs = require('fs');
        this.pictures = [];
    }

    read() {
        fs.readFile('./posts.json', (err, data)=> {
            if(err) {
                throw err;
            }else {
               return this.pictures = data;
            }
        });
    }
}

module.exports = Database;

【问题讨论】:

  • 你写的是 fs.readFile 而不是 THIS.fs

标签: javascript node.js express ecmascript-6 server


【解决方案1】:

使用:

this.fs.readFile 在您的 read 函数中,而不是 fs.readFile。由于您在构造函数中需要它,并将其分配给this.fs

或者requirefs模块在db.js开头

const fs = require('fs');

在没有this的情况下使用它。

【讨论】:

  • 他实际上需要它来初始化一个属性值。 OP忘记使用“this”关键字
【解决方案2】:

您在尝试访问您在构造函数中使用this.fs = require('fs') 初始化的fs 属性时忘记写this 关键字。

你用它来访问pictures属性,但不是fs

【讨论】:

    猜你喜欢
    • 2011-11-27
    • 2019-08-13
    • 2018-06-12
    • 1970-01-01
    • 2020-11-19
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多