How to set variable containing token and then use in subsequent requests

I have a request that retrieves an api token. I’ve configured this script to extract the token from the response body and set an environment variable. The response body comes back quoted like this:

“token string”

My script to extract and set variable:

setEnvironmentVariable(“TOKEN”, pm.response.text().stringWithQuotes.replace(/"/g, ‘’));

How do I then use this?

I add a second request, and try and reference this variable name when setting the authorization header and it doesn’t recognize it.

Note: This API uses basic auth with a token as well, it just ignores the username. So in my code, I do base64 encode “:”+TOKEN. It does not accept it as a bearer token.

Hey @rhugga :waving_hand:t3:

Welcome to the Postman community! :postman:

Would you be able to share some images of your actual response body, please?

From your script, that looks like you’re using some very old syntax, has that been taken/sourced from a blog?

The newer sandbox syntax would be:

pm.environment.set()

As you’re trying to set an environment variable in the script, do you have an environment created and active, the the request is executed?

It looks like your token extraction is fine, but ensure the quotes are removed when storing it. In the next request, reference the environment variable exactly as it’s named, and make sure to encode it properly for Basic Auth. This should allow the request to recognize the token correctly.