Linked Questions

Popular Questions

Can't POST through React to Rails API

Asked by At

I'm trying to use fetch() to POST React form data to my Rails API, but my error within the Network tab of chrome dev tools returns:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot POST /undefined/cars</pre>
</body>
</html>

The error in the console states the "Unexpected token '<'" indicating that my response is being sent as HTML instead of JSON, but I'm not sure why it's not converting.

Here's my fetch request:

export const createCar = car => {
return dispatch => {
    return fetch(`${API_URL}/cars`, {
        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'))
}

}

Could someone please help me with this? Thanks.

Related Questions