Home > Mobile >  Cannot get form data from POST request
Cannot get form data from POST request

Time:07-14

When I send the form data and then try to log 'req.file' or 'req.body.description' on the backend, I get 'undefined'. If I just log 'req.body', then I get:

------WebKitFormBoundarydyAbqZv2voxZv0ZA Content-Disposition: form-data; name="image"; filename="test.png" Content-Type: image/png

------WebKitFormBoundarydyAbqZv2voxZv0ZA Content-Disposition: form-data; name="description"

test123 ------WebKitFormBoundarydyAbqZv2voxZv0ZA--

// Front-End (Next.js)

const AddPhotos = () => {
  const uploadImg = async (e) => {
    e.preventDefault();
    try {
      const file = e.target.querySelector('#image').files[0];
      const desc = e.target.querySelector('#desc').value;
      
      const formData = new FormData();
      formData.append('image', file);
      formData.append('description', desc);
      
      const res = await fetch('/api/uploadImg', {
        method: 'POST',
        headers: {
          'Content-Type': 'multipart/form-data'
        },
        body: formData
      });
      
      const data = await res.json();
      console.log(data);
    } catch (err) {
        console.log(err)
    }
  }
  
  return (
    <div>
      <form onSubmit={uploadImg}>
        <input
          type='file'
          name='image'
          id='image'
          accept='image/*'
        />
        <input type='text' id='desc' />
        <input type='submit' value='Upload'/>
      </form>
    </div>
  );
};

export default AddPhotos;


// Back-End (Next.js built-in API)

export default async function handler(req, res) {
  try {
    const file = req.file;
    const desc = req.body.description;
    
    console.log(file)
    
    res.json(true);
  } catch(err) {
      console.log(err)
      res.status(404).json(`${err}`)
  }
}

CodePudding user response:

You should follow this simple guide as it expains briefly how to make a middleware that's gonna parse the form-data with next-connect, and dedicated to next.js.

Next.js (Express.js) Snippet

const { createRouter } = require("next-connect");
import multer from "multer";

const upload = multer({
    storage: multer.diskStorage({
        destination: (req, file, cb) => {
            cb(null, "public")
        },
        filename: (req, file, cb) => cb(null, file.originalname)
    })
});

const apiRouter = createRouter();

apiRouter.use(upload.single("file"))
    .post((req, res) => {
    console.log(req.file)
    res.send();
});

export default apiRouter.handler({
    one rror: (err, req, res) => {
        console.error(err.stack);
        res.status(500).end("Something broke!");
    },
    onNoMatch: (req, res) => {
        res.status(404).end("Page is not found");
    }
});

export const config = {
    api: {
        bodyParser: false
    }
}

Index.js Hello page edited with a sample input

const axios = require("axios");

async function uploadFile(e) {
    const firstFile = e?.target?.files?.[0];
    const postData = new FormData();
    postData.append("file", firstFile);
    await axios.post("/api/hello", postData, {
        headers: {
            "Content-Type": "multipart/form-data"
        }
    });
}

export default function Home() {
    return (
        <div>
            <input type="file" name="test" id="test" onChange={uploadFile}/>
        </div>
    );
}

  • Related