【发布时间】:2020-12-24 00:12:23
【问题描述】:
这就是我设法读取 json 文件的方法
posts.js 文件
const PATH = require('/Users/jorgesisco/Dropbox/Programming_Practice/Web_Development/PWJ/Module-8/Blog/pwj-module-8-my-blog-api/exercise/data.json');
class Post {
get() {
// get posts
}
getIndividualBlog() {
// get one blog post
}
addNewPost() {
// add new post
}
readData() {
return PATH;
}
}
module.exports = Post;
现在在 app.js 中我调用该函数,我可以在 postman 中看到 json 文件。
// 1st import express
const express = require('express');
const app = express();
const Post = require('./api/models/posts');
const postsData = new Post();
const posts = [
{
id: '1581461442206',
title: 'This is a New Blog Post',
content: 'This is the content! ',
post_image: 'uploads/post-image-1581461442199.jpg',
added_date: '1581461442206',
},
];
// const result = posts.flatMap(Object.values);
app.get('/api/posts', (req, res) => {
res.status(200).send(postsData.readData());//here I call the function to see json file in postman
});
app.listen(3000, () => console.log('listening on http://localhost:3000'));
我认为我不应该使用 json 文件的整个文件路径,但是当我只使用 ./data.json 之类的东西时,会发生错误,因为它找不到 json 文件。
【问题讨论】:
标签: javascript node.js json require