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.