Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reactjs redux: Fetch PUT method sending only an OPTIONS method, even when the status is 200

I am sending a PUT method as follow (checking with chrome):

function checkStatus(response) {
  if (response.status >= 200 && response.status < 300) {
    console.log("status: ", response.statusText);
    return response
  } else {
    var error = new Error(response.statusText)
    error.response = response
    throw error
  }
}

import fetch from 'isomorphic-fetch'
return dispatch => {
        dispatch(requestPosts(data));
        return fetch('/trendings', {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                Authorization: Config.token
            },
            body: JSON.stringify(data),
        })
        .then(checkStatus)
        .then(reponse => {
            console.log('request succeeded with JSON response', data);
            dispatch(successSent("The output list has been successfully sent!"));
        }).catch(err => {
            console.log('request failed', err);
            dispatch(failSent("Error on sending request: " + err));
        });

and the problem is that it's returning an OPTIONS method with status 200 only.

The problem is that it should follow with the PUT method. Furthermore, it should return an error as the API endpoint isn't ready yet.

Am I missing something?

like image 353
Jay Cee Avatar asked May 12 '16 22:05

Jay Cee


1 Answers

You need to add credentials: 'same-origin' and to remove the 'Content-Type' : 'application.json' from headers list since isomorphic-fetch doesn't seem to handle it well to avoid this issue otherwise the first isormophic-fetch will only triggers the OPTION request to fetch information about the server (it's the default browser behavior for cross origin requests) :

import fetch from 'isomorphic-fetch'
return dispatch => {
        dispatch(requestPosts(data));
        return fetch('/trendings', {
            method: 'PUT',
            headers: {
                'Accept': 'application/json',
                'Authorization': Config.token
            },
            credentials: 'same-origin', // you need to add this line
            body: JSON.stringify(data),
        })
        .then(checkStatus)
        .then(reponse => {
            console.log('request succeeded with JSON response', data);
            dispatch(successSent("The output list has been successfully sent!"));
        }).catch(err => {
            console.log('request failed', err);
            dispatch(failSent("Error on sending request: " + err));
        });
like image 92
Pierre Criulanscy Avatar answered Oct 28 '22 23:10

Pierre Criulanscy