Reputation: 1
I amm trying to return API data i have key and username can anyone give me Javascript
code to console.log
the returned object.
button.onclick = function(){
var reg = document.getElementById("symb").value;
document.getElementById("databox").innerHTML = " ";
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json")
xhr.setRequestHeader("user","my name");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.email + ", " + json.password);
}
};
var data = JSON.stringify({"registrationNumber": "rf23mzv"});
xhr.send(data);
}
Upvotes: 0
Views: 2994
Reputation: 1847
The link you posted specifies
Every client is issued an API Key which is passed into the request as a mandatory named header as follows:
name: x-api-key value: {supplied API key}
Thus, you have to add this header to your request, and provide the API key that you have been given.
If you want to keep using XHR, add it like you add the Content-Type
header:
xhr.setRequestHeader("x-api-key", "put-your-api-key-here");
IMO this is much easier with the fetch api instead of the classic XHR. It should let you replace all your snippet with something like this:
fetch('https://driver-vehicle-licensing.api.gov.uk/vehicle-enquiry/v1/vehicles', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': 'put-your-api-key-here',
},
body: JSON.stringify({registrationNumber: 'rf23mzv'}),
})
.then(res => res.json())
.then(console.log)
Upvotes: 1