Reactjs redux:Fetch PUT方法只发送一个OPTIONS方法,即使状态为200

时间:2016-05-12 22:58:30

标签: reactjs fetch redux

我发送的PUT方法如下(用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));
        });

问题是它只返回状态为200的OPTIONS方法。

问题是它应该遵循PUT方法。此外,它应该返回错误,因为API端点还没有准备好。

我错过了什么吗?

1 个答案:

答案 0 :(得分:3)

您需要添加credentials: 'same-origin'并从isomorphic-fetch doesn't seem to handle it well开始删除标题列表中的'Content-Type' : 'application.json'以避免此问题,否则第一个isormophic-fetch只会触发OPTION请求获取有关服务器的信息(这是跨源请求的默认浏览器行为):

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));
        });