Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

cypress - How Can We Get Token And Show It In Response

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
    }
}
question from:https://stackoverflow.com/questions/65831509/how-can-we-get-token-and-show-it-in-response

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
    })
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...