Chrome获取Set-cookie标头,但未将其放入新请求中 [英] Chrome get Set-cookie header but doesnt put it in a new requests

查看:251
本文介绍了Chrome获取Set-cookie标头,但未将其放入新请求中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用前端的 React Native 和后端的NodeJ来开发移动应用.我为此应用程序添加了身份验证机制.后端工作正常.我已经与邮递员进行了测试.在使用正确的数据登录请求之后,服务器向我发送了一个cookie,其中包含" Set-cookie"标头.然后,我将下一个请求标头放置为"cookie"我得到了我的数据.但是,当我使用React Native部件时,它的工作方式有所不同.我现在正在使用 Chrome浏览器来测试应用,并且我可以看到浏览器通过登录请求的响应获得了一个set-cookie标头,(此外,我还看到服务器使用用户创建了一个新cookie信息).但是对于下一个请求(例如其"/home"),它不会将cookie发送回去,因此服务器无法识别用户并创建新的cookie(其中没有用户信息)并返回403响应

I m working a Mobile app using React Native at the front end, NodeJs at the back end. I put an authentication mechanism for this app. Back-end works fine. I've tested with the postman. After login request with correct data, the server sends me a cookie in "Set-cookie" header. Then I put my next request header as "cookie" and I got my data. However, it works differently when I m working with React Native part. I m using Chrome browser to test app for now, and I can see that browser gets a set-cookie header with the response from Login request, (plus I've seen server created a new cookie with user info in it). But for the next request (say its "/home"), it doesn't send the cookie back, so the server doesn't recognize the user and creates a new cookie (with no user info in it) and returns 403 response.

有些解决方案被人们建议您这样做.我在这里分享这些内容,但没有一个对我有用.

There are some solutions that people suggest that you should do. I m sharing those here but none of them worked for me.

    在请求或axios对象中使用 withCredentials:true 输入
  1. (不解决问题)
  2. 为服务器中的cookie设置 httpOnly:false (没有解决问题)
  3. 将corsOptions设置为var corsOptions = {来源:"*",凭据:true, exposedHeaders:["Set-Cookie"] };(仍然无法正常工作)
  4. 我还使用 universal-cookie 库从前端访问cookie数据,但也无法达到cookie值
  5. 在URL中使用 127.0.0.1代替"localhost" 也不起作用(有人说cookie在第一级域中不起作用)
  1. put with withCredentials: true in your request or axios object (didnt solve the problem)
  2. set httpOnly:false for cookie in server (didnt solve the problem)
  3. set corsOptions as var corsOptions = { origin: '*',credentials: true,exposedHeaders: ["Set-Cookie"]}; (still not working)
  4. I also use universal-cookie library to reach cookie data from front end, but it also cannot reach the cookie value
  5. Using 127.0.0.1 instead of "localhost" in url also doesnt work (some says cookies dont work in first level domains)

这是我的React Native-Axios代码

Here is my React Native - Axios code

const axiosObj = axios.create({
    baseURL:"http://localhost:3000/",
    headers: {
      'Content-Type': 'application/json',
    },
    responseType: 'json',
    withCredentials: true, 
  });

export function get(url){
    return new Promise(function(resolve,reject){
        axiosObj.get(url).then(res => {
            console.log(res)
            return res.data
        })
    }) 
};

export function post(url,data){
    return new Promise(function(resolve,reject){
        axiosObj.post(url,data).then(res => {
            console.log(res.headers)
            const cookies = new Cookies(res.headers.cookie);
        console.log("document cookie",document.cookie)    
        console.log(cookies.getAll()); 
            resolve(res)
        })
    }) 
}

在后端是相关代码

 var app = express();
app.use(cookieParser('keyboard cat'));


var corsOptions = {
  origin: '*',
  credentials: true,
  exposedHeaders: ["Set-Cookie"]
 };
app.use(cors(corsOptions))
app.use(logger('dev'));
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: false })); 
app.use(express.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

//session settings
app.use(session({
  genid: (req) => {
    console.log('Inside the session middleware')
    console.log(req.sessionID)
    return uuidv4(); // use UUIDs for session IDs
  },
  store: new FileStore(),
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  cookie: { httpOnly: false,
    expires: new Date(Date.now() + (30 * 86400 * 1000))}
}))

这是我登录后在服务器上的会话文件

This is my session file at the server after Login

{"cookie":{"originalMaxAge":2591995208,"expires":"2020-09-22T20:22:56.993Z","httpOnly":false,"path":"/"},"passport":{"user":{"_id":"5f307fc99f5c667918a56122","username":"test","__v":0}},"__lastAccess":1598214181785}

这里可能是什么问题?有什么想法吗?

What can be the problem here? Any ideas?

我了解到未达到"Set-cookie"从前端(JS)正常.(尽管在某些网站上,它说您可以在cookie设置中放入 httpOnly:false ,它可以解决此问题).因此,如果我没有到达前端代码中的标头,则实际上并不重要.我得到了"set-cookie"我的响应标头中的标头和 chrome无法识别cookie并将其放在f12中的cookie部分中(也没有在req.header中设置它).这就是问题所在

edit : I've learned that not reaching "Set-cookie" is normal from front-end (JS). (although in some websites, its said that you can put httpOnly: false in cookie settings and it solves this problem). So it actually doesn't matter if I don't reach the header inside the front end code. I got "set-cookie" header in my response header and chrome doesn't recognize the cookie and put it in cookies section in f12 (also doesn't set it in req.header). That's the problem here

我对自己的问题有一些想法.

Edit 2: I have some ideas about my problem.

  • 由于我正在使用React Native,并且不能在Chrome浏览器中使用,因此可能会以某种方式导致浏览器未设置Cookie.我将创建一个react项目,并尝试从那里到达cookie.=>我解决了与该问题无关的问题.尽管我在测试应用程序时解决了问题

我有一个"service-worker.js"我的本机代码错误.看起来它不会影响代码的功能,但可能会以某种方式影响此cookie情况=>解决问题后,我仍然遇到此错误,因此与该错误无关.

I got a "service-worker.js" error with my react-native code. It doesn't look like it affects the functionality of the code but it might be somehow affected this cookie situation => After solving the problem I still got this error, so it was not related to this.

我还尝试了一个针对cookie的react native应用程序(react-native-cookie),但它的代码仅适用于android或ios,因此不适用于浏览器.

I also tried a react native app for cookies (react-native-cookie) but it has codes only working with android or ios so it didn't work for the browser.

推荐答案

我解决了我的问题.看来我的程式码有2个问题.第一个是在具有cors设置的服务器中.第一个版本是这样的:

I solved my problems. It looks like i have 2 problems with my code. First one is in server with cors settings. The first version was like this :

var cors = require('cors');
var corsOptions = {
  origin: '*',
  credentials: true,
  exposedHeaders: ["set-cookie"]
 };
app.use(cors(corsOptions))

所以基本上我是使用cors模块进行设置的.当我为测试创建一个React应用时,出现了cors错误(原始错误).不知何故,我的cors设置不适用于该库.所以我用下面的代码更改了代码.

So basically I was using the cors module for settings. When I create a React app for the test I got a cors error(origin error). Somehow my cors settings didn't work with the library. So I changed this code with the below.

app.use(function (req, res, next) {
     // Website you wish to allow to connect
     res.setHeader('Access-Control-Allow-Origin', '*');
     // Request methods you wish to allow
     res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
     // Request headers you wish to allow
     res.setHeader('Access-Control-Allow-Headers', 'Origin,X-Requested-With,content-type,set-cookie');
     // Set to true if you need the website to include cookies in the requests sent
     // to the API (e.g. in case you use sessions)
     res.setHeader('Access-Control-Allow-Credentials', true);
  
     // Pass to next layer of middleware
     next();
   });

,我仍然有一些错误提示.可能会出现cors错误的另一个原因是chromes同源策略.我正在使用Windows 10,所以我打开了下面的搜索栏,然后粘贴到那里

and I still had some cors error. One other reason you might get a cors error is that chromes same-origin policy. I m using windows 10 so I opened search bar below and paste there

 chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

一个没有Web安全策略的新chrome浏览器打开了.然后我的react应用程序运行良好.我可以使用 document.cookie 来访问cookie,同样在f12中的应用程序选项卡>>下.cookie,我可以看到我的cookie.因此,谷歌浏览器保存了我的Cookie.在同一个Chrome窗口中,我运行我的react本机应用程序,它也成功运行.因此,我认为这仅仅是因为chrome的安全策略并重新更改了cors设置,然后我又开始出现错误.

A new chrome browser opened with no web security policy. Then my react app worked fine.I could reach the cookie using document.cookie, also in f12 under application tab >> cookies, I could be able to see my cookie. So google chrome saved my cookie. In the same chrome window, I run my react native app and it also worked successfully. So I thought it was only because security policy of chrome and change my cors settings back and I started to get an error again.

因此,总而言之,我不得不更改2件事.

So in conclusion, I had to change 2 things.

  1. Cors模块不起作用,我手动设置了标头,它们工作正常.
  2. 我必须禁用Chrome的同源策略

这篇关于Chrome获取Set-cookie标头,但未将其放入新请求中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆