Skip to content

Read Header and Body After Get or Post

Manabu Tokunaga edited this page Mar 17, 2017 · 3 revisions

Problem

You want to read the HTTP status after issuing a POST or GET

Solution

The following code will get the HTTP Status code, an item from the HTTP header with "message" as its title, and Json coded Body.

Note: The XHR extract takes a string by definition. This is not quite right as you can pass the JSON structure and it will appear as the same JSON structure as in the example below. But because of this you would need to cast it to "any" if you are not returning a string.

m.request(
           {
                method: "POST",
                url: "/example/greeter",
                data: payload,
                withCredentials: true,
                extract: (xhr) => {
                    return {
                        status:  xhr.status,
                        message: xhr.getResponseHeader("message"),
                        body: xhr.responseText
                    } as any
                }
            }
        )
            .then(resp => {
                let j = JSON.parse(resp.body);
                alert(`Awesome! ${resp.status} ${j.greeting}, ${resp.message}`);
            }).catch(why => {
              
                alert(`Not OK: ${why}`)
        })