Theo
Theo

Reputation: 2792

Postman: How to open a browser window/redirect from a pre-request script?

I have a pre-request script in Postman that retrieves an internal identifier from an API based on a CLIENT_COMMON_NAME variable. To authenticate, I am using my browser cookies with Postman Interceptor and Interceptor Bridge.

The pre-request script works fine when logged in, but for convenience, I want it to redirect me to the internal login page https://auth.example.com if I'm currently not logged in.

My code:

const BASE_URL = "https://auth.example.com";
const API_CLIENT = pm.globals.get("API_CLIENT");
pm.cookies.jar().getAll(BASE_URL, function (error, cookies) {
  pm.sendRequest(
    {
      url: `${BASE_URL}/identitygen?user=${API_CLIENT}`,
      cookies: cookies,
    },
    function (err, res) {
      try {
        err === null &&
          pm.globals.set("TECHNICAL_API_IDENTITY", res.json().identity);
      } catch (error) {
        // How can I redirect to https://auth.example.com here?
      }
    }
  );
});

What would be the best way to redirect to the login page in this scenario? I'm not sure how to achieve this using JavaScript in the Postman pre-request script. Any help would be appreciated.

Upvotes: 0

Views: 1360

Answers (1)

Christian Baumann
Christian Baumann

Reputation: 3434

You can use pm.request to redirect to the login page:

const BASE_URL = "https://auth.example.com";
const API_CLIENT = pm.globals.get("API_CLIENT");
pm.cookies.jar().getAll(BASE_URL, function (error, cookies) {
  pm.sendRequest(
    {
      url: `${BASE_URL}/identitygen?user=${API_CLIENT}`,
      cookies: cookies,
    },
    function (err, res) {
      try {
        if (err === null) {
          pm.globals.set("TECHNICAL_API_IDENTITY", res.json().identity);
        } else {
          // Handle error and redirect to login page
          pm.request.redirect(`${BASE_URL}/login`);
        }
      } catch (error) {
        // Handle error and redirect to login page
        pm.request.redirect(`${BASE_URL}/login`);
      }
    }
  );
});

I added an else block after checking if err === null.
If an error occurs during the API request, it will execute the code inside the else block and redirect to the login page using pm.request.redirect.

Similarly, if an error occurs while parsing the response JSON, it will also redirect to the login page.

Upvotes: 0

Related Questions