本文介绍了Next Js 服务端 Api 读写 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Next.js 为自己编写一个基本的本地 api,它是一个时间线生成器,但实际上我一直无法从 api 文件夹中读取文件.

I'm trying to write a basic local api for myself using Next.js, it is a timeline generator, and I am stuck at actually reading the file from the api folder.

我在本地应用程序中想要什么:

What do I want in my local aplication:

1.一个简单的页面,我可以在其中输入事件,带有日期和描述

1.A simple page where I can input an event, with a date and description

2.在某处打开一个 list.json 文件并将新事件推送到该 json 文件,并在其上写入.

2.Open a list.json file somewhere and push that new event to that json file, writing on it.

我目前在做什么以及我被困在哪里:

What I am currently doing and where I am stuck:

我知道我们不能在客户端写入文件,所以我开始查看下一个 js 中的 api 路由以访问 JSON 文件,但我什至无法读取它!

I am aware we cant write on files on the client side, so I started looking at the api routes in next js to access the JSON file, but I cannot even manage to read it!

我在 pages 文件夹中有一个 api 文件夹,在这个 api 文件夹中我有两个文件:一个是 list.json 文件,我之前在其中手动编写了一些带有相应日期的事件;另一个是getlist.js,代码如下:

I have an api folder inside pages folder, and in this api folder I have two files: one is the list.json file, where I previously manually write some events with respective dates; and the other is getlist.js, with this code:

var fs = require('fs');

export default function getList(req, res) {
    const rawList = fs.readFile('list.json');
    var list = JSON.parse(rawList);
    res.json(list);
}

现在在 pages 文件夹上我有一个 index.js 文件,我尝试使用 getStaticProps() 访问这个 getlist.js api,如下所示:

Now on the pages folder I have a index.js file where I try to access this getlist.js api using getStaticProps(), like this:

import getlist from './api/getlist'

export async function getStaticProps(){

    var list = getlist();

    return {
        props: {
            list
        }
    }
}

我尝试过使用其他东西(例如 fecth 函数)来访问 getlist.js,但我所做的一切似乎都不起作用.

I have tried using other stuff, like the fecth function, to get to getlist.js, but nothing I do seems to work.

谁能帮帮我?

既然我已经在这里了,我将如何设法从客户端页面中已有的表单中获取输入并将其写入我的 api 文件夹中的 list.json 文件?

And since I'm already in here, how would I manage to get the input from the form I already have in my client side page and write it to that list.json file in my api folder?

推荐答案

next.js中读取json的方式有两种:

There are two ways how you can read json in next.js:

  • getStaticProps [https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation]
  • 内部导入
  • Import inside getStaticProps [https://nextjs.org/docs/basic-features/data-fetching#getstaticprops-static-generation]

    export async function getStaticProps(context){
      const example = await import('./api/example.json');
      return {props: {example: example.default}}
    }

  • 导入或读取 api 文件夹 [https://nextjs.org/docs/api-routes/introduction] 内的 handler 函数:
    • Import or read in handler function inside api folder [https://nextjs.org/docs/api-routes/introduction]:
    • 
          const fs = require('fs');
      
          export default async function handler (req, res) {
            const example = await fs.readFile('./example.json');
            return res.status(200).json({example});
          }
      
      

      为了编写 *.json 文件,您需要将带有值的请求发送到服务器 api(之前提到的 api 文件夹中的 handler).

      In order to write *.json file you need to send request with value to the server api (handler from api folder that was mentioned before).

      这就是编写 json 的部分的样子:

      That's how the part to write json will look like:

      
          const fs = require('fs');
      
          export default async function handler(req, res) {
            //...
            if (req.method === 'POST'){
              fs.writeFileSync('./example.json', JSON.stringify(req.body))
              return res.status(200).json({});
            }
            //...
          }
      
      

      这篇关于Next Js 服务端 Api 读写 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 20:23