Cypress中cy.request无法设置credentials:'include'致401,求解决方案
问题:Cypress cy.request 无法设置 credentials: 'include' 导致401未授权
背景
在浏览器开发者控制台中,以下fetch代码可正常运行:
fetch('https://api.my-url.com', { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', 'Cookie': document.cookie } })
尝试将其转换为Cypress的cy.request代码,写法如下:
cy.request({ method: 'POST', credentials: "include", // 这是有问题的代码行 url: 'https://api.my-url.com', headers: { 'Content-Type': 'application/json', 'Cookie': document.cookie } })
但cy.request的RequestOptions仅包含以下选项:
auth, body, encoding, followRedirect, form, gzip, headers, method
因此无法通过上述方式设置credentials: 'include'。移除该选项发送请求时,收到如下错误:
我们从您的Web服务器收到的响应是:401: Unauthorized
解决办法
利用Cypress自动管理Cookie的特性:
Cypress默认会自动保留和发送测试过程中产生的Cookie,无需手动通过document.cookie获取。先访问目标站点的页面(比如登录页)完成登录,让Cypress自动捕获有效Cookie,之后直接发送请求即可:// 先访问站点获取Cookie cy.visit('https://your-site.com/login') // 执行登录操作,Cypress自动保存Cookie cy.request({ method: 'POST', url: 'https://api.my-url.com', headers: { 'Content-Type': 'application/json' }, body: { /* 你的请求数据 */ } })手动传递正确的Cookie值:
cy.request运行在Node环境,无法直接访问浏览器的document对象,所以不能用document.cookie。可以通过cy.getCookie()获取指定Cookie后手动设置:cy.getCookie('your-target-cookie').then(cookie => { cy.request({ method: 'POST', url: 'https://api.my-url.com', headers: { 'Content-Type': 'application/json', 'Cookie': `${cookie.name}=${cookie.value}` }, body: { /* 请求数据 */ } }) })使用
cy.intercept处理页面触发的请求:
如果API请求是由页面操作触发的,可通过cy.intercept监听请求,确保凭证正确携带:cy.intercept('POST', 'https://api.my-url.com').as('apiRequest') // 触发页面上的请求操作,比如点击提交按钮 cy.get('#submit-btn').click() cy.wait('@apiRequest').then(interception => { // 验证请求是否携带了正确的Cookie expect(interception.request.headers.cookie).to.exist })
内容的提问来源于stack exchange,提问作者Ivan Haralampiev
相关产品推荐
相关产品推荐

