我在我的Reaction Native项目中使用了Fetch API.我向服务器发出HTTP POST请求,该服务器需要用户名和密码.如果登录成功,服务器在登录页面中设置会话cookie,然后重定向到另一个名为博客的网页.Fetch API收到来自博客的响应,该博客没有会话cookie.因此,我需要在重定向发生之前捕获重定向并存储会话cookie.
在文件中,它说redirect: 'manual'
个人应该可以完成这项工作.然而,我还是从最后一页得到了回复.Fetch API-response.redirected
返回undefined
看不到重定向.但是请求和响应的URL是不同的.潜在的问题可能出在哪里?
const url = 'url of a website ( cannot show it to you )';
// login request
const login = (profileName, password) => {
const details = {
benutzername: profileName,
passwort: password,
};
const formBody = Object.keys(details)
.map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(details[key])}`)
.join('&');
console.log(`formBody to be sent: ${formBody}`);
fetch(url, {
method: 'POST',
headers: {
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
'Content-Type': 'application/x-www-form-urlencoded',
},
body: formBody,
redirect: 'manual',
})
.then((response) => {
console.log('! response type !');
console.log(response.type);
console.log('! is redirected !');
console.log(response.redirected);
console.log('! response console log !');
console.log(response.url);
console.log('! response status console log !');
console.log(response.status);
return response.headers;
})
.then((headers) => {
console.log('! headers for each !');
headers.forEach((value, key) => {
console.log(`${key} ==> ${value}`);
});
return headers;
})
.catch((error) => console.log(`error: ${error}`));
};
export { login };
以下是浏览器中的网络活动截图:
Login:
Blog:
以下是日志(log):
LOG ! response type !
LOG default
LOG ! is redirected !
LOG undefined
LOG ! response console log !
LOG https://.../Blog.xhtml?faces-redirect=true&dswid=-8890
LOG ! response status console log !
LOG 200
LOG ! headers for each !
LOG cache-control ==> no-cache, no-store, must-revalidate
LOG content-encoding ==> gzip
LOG content-type ==> text/html;charset=UTF-8
LOG date ==> Sun, 23 Jul 2023 14:54:59 GMT
LOG expires ==> 0
LOG pragma ==> no-cache
LOG server ==> Apache
LOG set-cookie ==> dsrwid--8890=-8890; path=/; secure; Max-Age=60; Expires=Sun, 23-Jul-2023 14:55:59 GMT; SameSite=None
LOG vary ==> Accept-Encoding