React native fetch 遇到的坑

2018-04-24  本文已影响595人  街角仰望

1、在请求数据的时候,一般情况下我们会直接提交Content-typejson数据格式的请求。类似

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    firstParam: 'yourValue',
    secondParam: 'yourOtherValue',
  })
})

当我开始请求登录接口的时候,发现上面的请求方法失效了,想了好多办法都不知道问题出在哪里,最后试了下抓包,才发现原来请求登录接口的时候,content-typeapplication/x-www-form-urlencode,于是我搜了下这方面的知识。我们在提交表单的时候,form表单参数中会有一个enctype的参数。enctype指定了HTTP请求的Content-Type。默认情况下,HTMLform表单的enctype=application/x-www-form-urlencodedapplication/x-www-form-urlencoded是指表单的提交,并且将提交的数据进行urlencode。默认情况下,我们所有的表单提交都是通过这种默认的方式实现的。文档中是有记载的:

fetch('https://mywebsite.com/endpoint/', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
  },
  body: 'key1=value1&key2=value2'
}

2、登录成功后如何获取headers里面的sessionid的问题。

登录成功之后,我们可以打印出上面的response,若是需要取出上面的sessionid,我们可以采用下面的方法,写法可能比较low,但是可以达到目的

//获取sid
var headers = response.headers.get("set-cookie");
var header = headers.split(";");
var sessionid;
for(var index = 0; index < header.length; index++)
{
    if(header[index].indexOf("JSESSIONID") > -1){
        sessionid = header[index].split("=")[1];
    }
}
//保存
AsyncStorage.setItem('sessionid', sessionid);

3、登录成功之后,后台需要根据sessionid来判断登录状态。当请求的接口是必须登录之后才能获得数据的时候,就不能用传统的写法来请求了。javascript使用fetch进行跨域请求时默认是不带cookie的,所以会造成session失效。那所以在登录请求的时候需要加上credentials: ‘include’这个字段。

fetch(Api.checkLoginSecurity , {
    credentials: 'include',
    method: 'POST',
    headers:{
        'Content-Type': 'application/x-www-form-urlencoded',
    },
    body: 'username='+ this.props.userName + '&password=' + this.userPassword
})

在需要登录后才能获取数据的接口也需要加上

fetch(url , {
    credentials: 'include',
    method: 'GET',
})

此处还要强调一下get请求和post请求,经别人提醒,发现虽然他写了个body= {*},让我误以为是用POST方式,其实body只是参数的字段,实际上用的还是GET请求,所以把POST改为GET(默认是GET,所以就不需要写method),因为GET无法在body里传参,也不需要header,直接把参数写在URL里,只有POST才是在body里传参。

参考:https://blog.csdn.net/meyin/article/details/73776548

上一篇下一篇

猜你喜欢

热点阅读