Search code examples
k6

How to make a simple POST request in k6 with multiple custom headers


I cannot get this script working for the life of me as I get error: INFO[0001] {"error":{"code":2,"message":"Invalid or Missing X-App-Token","documentation":""}}

However, a curl request with this header works fine. This is a custom header we use in our whole project. I can't find any examples of k6 with multiple headers passed in. The curl request also doesn't require accept header, so tried only passing in X-App-Token, no changes. Tried playing with the commas and parenthesis. I believe I'm passing in the header correctly.

import encoding from 'k6/encoding';
import http from 'k6/http';
import { check } from 'k6';

export default function () {

var url = 'https://api.mycompany.com/test/scenarios/PropertyManager';

const params = {
headers: {
  'X-App-Token':'<proprietary string>',
  'accept':'application/json' 
},
timeout: 2000,
};

let res = http.post(url, params);
console.log(res.body);

// Verify response 
check(res, {
'status is 200': (r) => r.status === 200
});

}

Solution

  • The 2-parameter http.post treats the 2nd parameter as the POST data, not params.

    You should use the 3-parameter http.post:

    let res = http.post(url, {}, params);
    

    Assuming you are sending a POST request with no POST data, otherwise modify the empty object.