React Native Fetch Api 无法设置 Cookie 标头

2022-01-20 00:00:00 fetch php javascript react-native

我正在开发一个 react native 应用程序和 php rest 服务作为后端.

I am developing a react native app and php rest service as backend.

当用户登录时,我使用 json_encode() 函数将用户和会话 ID 信息回显为 $response 数组.

When user login i echo user and session id info as $response array with json_encode() function.

$response['user'] 存储用户信息.$response['sessid'] 存储会话 ID.

$response['user'] stores user info. $response['sessid'] stores session id.

在 Postman 中,我可以将 Header 设置为 Cookie,并使用 sessionid 作为值.它完美地工作.但是在 fetch api 中我无法设置 Cookie 标头.

In Postman i can set a Header as Cookie and as value i use sessionid. It works perfectly. But in fetch api i can't set Cookie header.

这是我的代码:

const value = await AsyncStorage.getItem('sessid');
console.log("value" + value)
var url = 'http://192.168.1.27/zuper/test.php';
fetch(url, {
  method: 'GET', 
  headers:{
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'Cookie' : value
  }
}).then(  (response) => {
  console.warn(response)
 })

这是值变量的值:0d580f8b8e1e1ead1ce038cb12289a57

对这个获取的响应带有一个 php 错误,上面写着

Response for this fetch comes with a php error which says

用户未定义

从行 $_SESSION['user']['name']

推荐答案

你是对的.Cookie 列在禁止的标头名称中:

You are correct. Cookie is listed amoung the forbidden header names:

这些是被禁止的,所以用户代理仍然可以完全控制它们.

These are forbidden so the user agent remains in full control over them.

如果您想在 HTTP 请求中发送 Cookie,则必须先向使用 Set-Cookie 响应标头设置的同一来源发出 HTTP 请求.

If you want to send a Cookie in an HTTP request, then you must make a prior HTTP request to the same origin that uses a Set-Cookie response header to set it.

相关文章