class Request {

constructor() {
this.xhr = new XMLHttpRequest();
}

get(url) {
this.xhr.open(“GET”,url);

this.xhr.onload = () => {
console.log(“Xhr Onload İçi : “this);
if(this.xhr.status===200) {
console.log(this.xhr.responseText);
}
}

this.xhr.send();
}
}
const request = new Request();
const albums = request.get(“https://……”);
console.log(albums);

dersek böyle bir durumda rest daha dönmeden asenkron olarak console.log()
önce çalışır ve undefined yazar. Bu sorunumuzu da daha önce gördüğümüz
callback ile çözebiliriz.

class Request {

constructor() {
this.xhr = new XMLHttpRequest();
}

get(url,callback) {
this.xhr.open(“GET”,url);

this.xhr.onload = () => {
console.log(“Xhr Onload İçi : “this);
if(this.xhr.status===200) {
callback(null , this.xhr.responseText);
}
else {
callback(“Hata”, null); // Hata durumunu için yaptık.
}
}

this.xhr.send();
}
}
const request = new Request();
request.get(“https://……”, function(err, response) {
if(err ==null )
console.log(response);
else
console.log(err);

Bu şekilde çözebiliriz. Burada callback e 2 . parametre geçme sebebim bi hata durumunda da callback dönsün diye. Ancak bunu responseText null değer gönderip kontrol ederekte yapabilirdik diyebilirsiniz ancak server’dan response değeri null da gelebilir bunu bilemeyiz. O yüzden 2. parametre geçtik belki undefined felan verilebilirdi. 2.parametre cok onemli değil takma kafaya.

POST

class Request {

constructor() {
this.xhr = new XMLHttpRequest();
}

get(url,callback) {
this.xhr.open(“GET”,url);

this.xhr.onload = () => {
console.log(“Xhr Onload İçi : “this);
if(this.xhr.status===200) {
callback(null , this.xhr.responseText);
}
else {
callback(“Hata”, null); // Hata durumunu için yaptık.
}
}

this.xhr.send();
}

post(url,data,callback) {
this.xhr.open(“POST”,url);
this.xhr.setRequestHeader(“Content-type”,”application/json”);
//Birden fazla türde data yollayabileceğimiz için
// gönderdiğimiz datanın tipini belirtiyoruz.

this.xhr.onload = () => {
if(this.xhr.status ===201) // Request başarıyla yollandı ve yeni bir data yaratıldı.
callback(null,this.xhr.responseText);
else
callback(“Hata”,null);
}
this.xhr.send(JSON.stringify(data));
}
}
const request = new Request();
const data = {userId:2 , title:”Omer”};
request.post(“https://……”, data, function(err, response) {
if(err ==null )
console.log(response);
else
console.log(err);

PUT
Bir veriyi update etmemizi sağlayan bir request tipi.