-2

I have one request that I want to get token from response and save it in variable because I want to use it in another request as bearer token

/// <reference types="cypress" />
describe("Testing API Endpoints Using Cypress", () => {
    it("Login", () => {
        cy.request({
            method: "POST",
            url: "/creditonal",
            body: {
                "credentials": {
                    "username": "admin",
                    "password": "admin"
                }
            }.then((response) => {
                // Get token
            })
        })
    })
})

This is my response

{
    "status": "ok",
    "statusCode": "0000",
    "message": {
        "type": "",
        "text": ""
    },
    "errors": [],
    "data": {
        "accessToken": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVmYTk0YzYzNWRhOWU0NTY0NGYwM2ViMiIsImlzQ2xpZW50IjpmYWxzZSwiaWF0IjoxNjExMjQzNjYyLCJleHBBdCI6MTYxMTI0NzI2MiwiaXNzdWVyIjoiRHJvcHAgVGVjaG5vbG9naWVzIiwicm9sZXMiOlsiRVJ5eGc2Il19.V7cniqE9DrxPRn5GX9wQJtVwPnLrv5Hb3A1SxmBXOO4",
        "accessTokenExpiresAt": 3599,
        "refreshToken": "983e503a2b194a0190af4cdf0f4d471cf387e4d784044f6ca1fe3f942aad1b5f",
        "refreshTokenExpiresAt": 15548399
    }
}
Ken White
  • 123,280
  • 14
  • 225
  • 444

2 Answers2

0

You can use token from from request 1 and pass it onto request 2 like this. I have currently used the token as an bearer authorization header.

cy.request({
    method: "POST",
    url: "/creditonal",
    body: {
        "credentials": {
            "username": "admin",
            "password": "admin"
        }
    }
}).then((response) => {
    const token = response.data.accessToken
    return token
}).then((token) => {
    //Use the value of token anywhere in the second request anywhere
    cy.request({
        method: 'GET',
        url: 'https//example.com',
        'auth': {
            'bearer': token
        }
    }).then((response) => {
        expect(response.status).to.eq(200)
    })
})
Alapan Das
  • 17,144
  • 3
  • 29
  • 52
0

I would suggest to go for alias which is easier to use. You just retrieve the response whenever you really need:

it("Login", () => {
  cy.request({
    method: "POST",
    url: "/creditonal",
    body: {
      "credentials": {
        "username": "admin",
        "password": "admin"
      }
    }
  }).as('login')

   // do more things

  cy.get('@login').then(response => {
    // whatever you want with response later on
  })
})
tmhao2005
  • 14,776
  • 2
  • 37
  • 44