'How to read a json file from the file system with Next.js and API routes?

I am trying to read a json object from the native file system API, however, when I try to read the object, I get a ------WebKitFormBoundaryolOMQEOtgU4o2qYu\r\nContent-Disposition string preeceding the actual json object.

Here is my json objec:

{
  "name": "Tyler",
  "age": 23,
  "hometown": "Chicago, IL",
  "interests": {
    "sports": "Baseball",
    "music": "Rock",
    "movies": "Star Wars"
  }
}

In my api routes in Next.js, this is my code:

const fs = require('fs')

export default function fileUpload(req, res) {
  if (req.method === 'POST') {
    // Process a POST request
    console.log('1. POST request received')
    console.log('********************')

    const file = JSON.stringify(req.body)

    console.log(file)

    console.log('********************')
  } else {
    // Handle any other HTTP method
    console.error(`Error: ${req.method} not supported`)
  }
}

Here is the output from that console log:

"------WebKitFormBoundaryolOMQEOtgU4o2qYu\r\nContent-Disposition: form-data; name=\"files\"; filename=\"demo.json\"\r\nContent-Type: application/json\r\n\r\n{\n  \"name\": \"Tyler\",\n  \"age\": 23,\n  \"hometown\": \"Chicago, IL\",\n  \"interests\": {\n    \"sports\": \"Baseball\",\n    \"music\": \"Rock\",\n    \"movies\": \"Star Wars\"\n  }\n}\n\r\n------WebKitFormBoundaryolOMQEOtgU4o2qYu--\r\n"

Here is my client side code when a a user uploads the json file:

// to handle file uploads
  const uploadFiles = async () => {
    // get the files from the fileList as an array
    let files = data.fileList
    // initialize formData object
    const formData = new FormData()
    // loop over files and add to formData
    files.forEach((file) => formData.append('files', file))

    // Upload the files as a POST request to the server using fetch
    // Note: /api/fileupload is not a real endpoint, it is just an example
    const response = await fetch('/api/fileupload', {
      method: 'POST',
      body: formData,
    })

    //successful file upload
    if (response.ok) {
      alert('Files uploaded successfully')
    } else {
      // unsuccessful file upload
      alert('Error uploading files')
    }
  }

Can I just get the json object? I don't need the meta data for this.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source