티스토리 뷰

Tool

[Postman] Pre-Request Script 사용하기

out of coding 2022. 12. 1. 08:27

Postman을 자주 사용하게 되면서 사용하게 되는 기능입니다.

 

우리가 개발을 할때에 access_token 기반의 로그인 서비스들의 경우에는 token이 만료되는 시점 때문에 지속적으로 로그인 관련 API를 호출하여 주어야 하는데 굉장히 불편하죠.

 

Pre-Request Script를 사용하면 됩니다.

저기 보이죠?

다음과 같이 script 코드를 작성하면 되는데요.

Postman이 지원하는 펑션들이 존재하기도 하기 때문에 사용이 편합니다.

pm.sendRequest({
  url: 'https://your-url/auth',
  method: 'POST',
  header: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: {
    mode: 'urlencoded',
    urlencoded: [
    {
      key: "id",
      value: "exam@exam.com",
      disabled: false
    },
    {
      key: "password",
      value: "string",
      disabled: false
    }]
  }
}, function (err, res) {
  res_data = res.json()
  console.log(res_data)
  pm.request.headers.add({
    key: "Authorization",
    value: "Bearer " + res_data.accessToken
  });
});

이 내용을 설명을 드리면,

sendRequest에서 url에 id와 password를 넣어서 access_token을 받아오는것이고요.

이후에 function (err, res) 를 통해서 받은 데이터를 json으로 변경하고 request의 header에 자동으로 넣어주는 방법입니다.

 

각 Key, URL 등은 각자의 환경에 따라서 변경하셔서 사용하시길 바래요.

그럼 즐코딩 되시길.

 
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함