最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Next Js Server Side Api Read and Write JSON - Stack Overflow

programmeradmin3浏览0评论

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.A simple page where I can input an event, with a date and description

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:

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!

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);
}
  

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
        }
    }
}

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

Can anyone help me?

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?

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.A simple page where I can input an event, with a date and description

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:

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!

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);
}
  

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
        }
    }
}

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

Can anyone help me?

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?

Share Improve this question asked Feb 25, 2021 at 14:23 Daniel GuedesDaniel Guedes 8372 gold badges9 silver badges18 bronze badges 4
  • 2 You probably mean to use readFileSync as readFile requires a callback function. – evolutionxbox Commented Feb 25, 2021 at 14:29
  • 1 You should call fs.readFile('list.json') directly from getStaticProps. getStaticProps only runs on the server, you should call any server-specific code directly from it. – juliomalves Commented Feb 25, 2021 at 14:29
  • Thank you! It worked! But now how can I handle a form submit to write on that file? I can't use getStaticProps to run server side code once the built is done everytime I press the form submit, so what other mechanism I should use? – Daniel Guedes Commented Feb 25, 2021 at 16:39
  • I coudn't figure out how to do this in Next witthout having to use a custom express server, so now Im not using next at all. – Daniel Guedes Commented Mar 8, 2021 at 15:42
Add a ment  | 

1 Answer 1

Reset to default 11

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

  • Import inside getStaticProps [https://nextjs/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}}
    }

  • Import or read in handler function inside api folder [https://nextjs/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});
    }

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).

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({});
      }
      //...
    }

发布评论

评论列表(0)

  1. 暂无评论