S.Esterkin
S.Esterkin

Reputation: 31

React Native / Expo: fetch throws "Network request failed" error on 401 response with formData content type

I am creating an expo app that interacts with a Django Rest Framework backend. I use fetch to get and post data to my server, and have JWT authentication set up. Fetch works as I expect it to sending json data to my server.

I am also trying to post some images to my server, and this works as expected until my token expires and the server returns a 401. When this happens on Android, fetch rather than resolving properly and having a response.status of 401, instead throws a TypeError: Network request failed. On iOS it just hangs.

Sample Code:

const formData = new FormData()
photos.map((photo, index) =>
  formData.append('images', {
    name: `test${index}.jpg`,
    type: 'image/jpeg',
    uri: photo.uri,
  }),
)
try {
  const response = await fetch(url, {
    body: formData,
    headers: {
      Authorization: `Bearer ${userToken}`,
    },
    method: 'POST'
  })
} catch (e) {
  console.log(e)
}

Fetch normally resolves properly when my server returns a 200 or 401, but when I post the image data, 200s resolve successfully but 401s cause fetch to throw a network request failed error. How do I stop this from happening?

Edit: Further research shows that the line of python code images = request.FILES.getlist('images', []) is crucial to not having this error. If I manually return before this line of code then I get the same issue. My guess is that this has something to do with the multipart upload being interrupted by an error but I am not sure how to handle this in the app.

Upvotes: 3

Views: 2186

Answers (1)

hong developer
hong developer

Reputation: 13926

Here is my simple code FormData with react-native to post request with string and image.

I used an image picker.

Could you switch headers?

let formdata = new FormData();

...

fetch('http://192.168.0.1/test',{
  method: 'post',
  headers: {
    'Content-Type': 'multipart/form-data',
  },
  body: formdata
  }).then(response => {
    alert("sucess")
  }).catch(err => {
    console.log(err)
  })  
});

Upvotes: 1

Related Questions