2

I have a NextJS application. In the client page I make a request to the API route, which then makes a PATCH request to the Django back-end.

It does not work and the image does not change, but I am able to successfully change it using something like Postman or Insomnia. Or If I decide to call the back-end directly from the client page.

Here is the code on the client page:

const UpdateImageField = async (event: any) => {
    event.preventDefault()

    var formdata = new FormData();
    formdata.append("coverfield", event.target.files[0], event.target.files[0]["name"]);

    const ress = await fetch(`/api/playlist/playlistimage/${playlistediting["id"]}`, {
        method: 'PATCH',
        headers: {
            'Accept': 'application/json',
        },
        body: formdata
    });
}

Here is the code on the API route page:

export default async (req, res) => {
    if (req.method === "PATCH") {
        const {
            playlistid
        } = req.query

        const cookies = cookie.parse(req.headers.cookie ?? '');
        const access = cookies.access ?? false;

        if (access === false) {
            return res.status(403).json({
                error: 'User forbidden from making the request'
            });
        }


        try {
            const apiRes = await fetch(`${API_URL}/playlist_api/playlists/${playlistid}/`, {
                method: 'PATCH',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW',
                    'Authorization': `Bearer ${access}`
                },
                body: req.body
            });

            const data = await apiRes.json();
            console.log(data)

            if (apiRes.status === 200) {
                return res.status(200).json({
                    updatedplaylist: data
                });
            } else {
                return res.status(apiRes.status).json({
                    error: data.error
                });
            }
        } catch (err) {
            return res.status(500).json({
                error: 'Something went wrong when changing the image'
            });
        }
    }
}

I get a 200 response from the back-end for the PATCH request but the image field does not actually change. I believe this has to do with the file in the request.body from Client Page to the API route.

VLAZ
  • 26,331
  • 9
  • 49
  • 67
kprime21
  • 37
  • 4
  • Take a look at your actual requests by mitm'ing it: `socat -v TCP-LISTEN:666,forever,reuseaddr,fork TCP:localhost:8000` – Ross Rogers Aug 25 '22 at 18:00
  • I can see the request being received in my back-end Django server. The problem is that the image file is not being sent from the NextJS API route. I am able to get it working if I do everything in the client and call the Django back-end directly. – kprime21 Aug 26 '22 at 04:05
  • 2
    Try using a `FormData` object instead https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects – Ross Rogers Aug 26 '22 at 12:55
  • I have tried using FormData with a Buffer in the API route as well and am still not having any success. – kprime21 Aug 26 '22 at 14:04
  • 2
    If you're using `FormData`, you shouldn't be setting this request header: `'Content-Type': 'multipart/form-data; boundary=---WebKitFormBoundary7MA4YWxkTrZu0gW',` – Ross Rogers Aug 26 '22 at 14:47
  • 1
    Wow. That was the fix. Thank you so much!! – kprime21 Aug 26 '22 at 14:53

0 Answers0