usebruno / bruno

Opensource IDE For Exploring and Testing Api's (lightweight alternative to postman/insomnia)
https://www.usebruno.com/
MIT License
28.11k stars 1.3k forks source link

Making an http request in pre-script #517

Open maniearla opened 1 year ago

maniearla commented 1 year ago

I have to make an http post request to get authorization token and pass that token in header.

In postman I used to make authorization request in pre-script and save that in a variable and use that in headers.

how can I do the same using bruno. Any suggestions will be helpful. Thanks in advance

scflode commented 1 year ago

I think this will do what you need: https://docs.usebruno.com/scripting/sync-requests.html

scflode commented 1 year ago

Note that there is a difference between setVar and setEnvVar.

const baseUrl = bru.getEnvVar("baseUrl");
const axios = require("axios");
const response = await axios.post(`${baseUrl}/auth`, {
  username: bru.getEnvVar("username"),
  password: bru.getEnvVar("password")
});
bru.setVar("accessToken", response.data.access_token);

With this you then can add {{ accessToken }} to Auth or a header value.

helloanoop commented 1 year ago

Thanks @scflode !

If all your requests (except login) require this header, you can set this in collection level headers. So that you don't have to duplicate this is every request.

philSixZero commented 1 year ago

@helloanoop Seems like the editor doesn't like the await keyword and axios is not defined when I run the code: grafik