James
James

Reputation: 461

Response Isn't Converting To JSON

I'm trying to take info from a React form and post it to my Rails database, but I get an error "unexpected token '<' at position 0" which means my response is still HTML and not JSON.

Here's my code:

export const createCar = car => {
return dispatch => {
    return fetch(`${API_URL}/cars/create`, {
        method: "POST",
        headers: {
            'Content-type': 'application/json'
        },
        body: JSON.stringify({ car: car })
    })
    .then(response => response.json())
    .then(car => {
        dispatch(addCar(car))
        dispatch(resetCarForm())
    })
    .catch(error => console.log(error + 'createCar POST failed'))
}

}

Is there a reason why it's not converting to JSON?

Additionally, I don't seem to be able to drop debugger into my code, or at least in this function - do I need to import it or something?

Upvotes: 0

Views: 55

Answers (1)

Matt Kuhns
Matt Kuhns

Reputation: 1368

I'm thinking that your server is sending you back HTML and then you are trying to parse it in response.json()

use a try/catch in this block:

export const createCar = car => {
return dispatch => {
    return fetch(`${API_URL}/cars/create`, {
        method: "POST",
        headers: {
            'Content-type': 'application/json'
        },
        body: JSON.stringify({ car: car })
    })
    .then(response => {
         try {
            return response.json()
         } catch(error) {
            console.error(error);
         }
    })
    .then(car => {
        dispatch(addCar(car))
        dispatch(resetCarForm())
    })
    .catch(error => console.log(error + 'createCar POST failed'))
}

Upvotes: 1

Related Questions