Search code examples
javascriptpromisexmlhttprequest

making HTTP post request using promises in javascript


I've tried to make a simple code to make http post and get requests with a contact data to json server using promises. But I see that I'm not posting correctly. I've put the promises inside a function constructor. But I don't find how to pass my contact data to the post promise. I get an error "Cannot access 'record' before initialization".

Please help me to find where does it go wrong, I've trying to solve it for 2 weeks, and still have no idea what to do with it.

//my code:
function http(url){
   let xhr = new XMLHttpRequest();
   this.post = new Promise((resolve, reject) => {
            xhr.open('POST', url);
            xhr.setRequestHeader('Content-type', 'application/json');
            xhr.onload = (e) => {
                 resolve(xhr.response);
            };
            xhr.send (JSON.stringify(record));
            xhr.onerror = (e) => {
                reject(xhr.state);  
            }}, record);
   
   this.get = new Promise((resolve, reject) => {
            xhr.open('GET', url);
            xhr.onload = (e) => {
                resolve(xhr.response);
             }; 
            xhr.send ();
            xhr.onerror = (e) => {
                reject(xhr.state);  
            }}); 
} 

//given code:
const httpClient = new http('http://localhost:3000/contacts');

let contact = {
    // add properties as per the data structure of the data fetched and retrieved
    "firstName": "jones",
    "lastName": "christi",
    "email": "[email protected]",
    "homeNo": "+1 890 765 3210",
    "workNo": "",
    "birthDate": "2001-16-9",
    "company": "",
    "jobTitle": "",
    "notes": "nth contact",
    "contactAddedOn": "2021-05-23T12:19:11.235Z"
  }

//my line:
let record = contact;

//given code:
httpClient
.post(record)
.then(response=>{
    alert('record added')
    console.log(response);
})
.catch(err=>{
    console.log(err);
});

httpClient
.get()
.then((response)=>{
    let data = '<ul>'
    let records = JSON.parse(response);
    records.forEach(r => {
        data+= `<li>${r.firstName}.${r.lastName}</li>`
    })
    data+='</ul>'
    document.body.innerHTML += data;
    console.log(response);
})
.catch(err=>{
    document.write(response);
    console.log(err)
});


Solution

  • First, check out hosting in js

    Also you need to implement the post and get as a method of function http(which will be used as class)

    But for now, what you wrote in your code is you just assigned a promise instance as a value to the key named post, and get like variables(field)

    let contact = {
        // add properties as per the data structure of the data fetched and retrieved
        "firstName": "jones",
        "lastName": "christi",
        "email": "[email protected]",
        "homeNo": "+1 890 765 3210",
        "workNo": "",
        "birthDate": "2001-16-9",
        "company": "",
        "jobTitle": "",
        "notes": "nth contact",
        "contactAddedOn": "2021-05-23T12:19:11.235Z"
      }
    //my line:
    let record = contact;
    
    function http(url){
       let xhr = new XMLHttpRequest();
       this.post = () => new Promise((resolve, reject) => {
                xhr.open('POST', url);
                xhr.setRequestHeader('Content-type', 'application/json');
                xhr.onload = (e) => {
                     resolve(xhr.response);
                };
                xhr.send (JSON.stringify(record));
                xhr.onerror = (e) => {
                    reject(xhr.state);  
                }}, record);
       
       this.get = () => new Promise((resolve, reject) => {
                xhr.open('GET', url);
                xhr.onload = (e) => {
                    resolve(xhr.response);
                 }; 
                xhr.send ();
                xhr.onerror = (e) => {
                    reject(xhr.state);  
                }}); 
    } 
    
    //given code:
    const httpClient = new http('http://localhost:3000/contacts');
    
    httpClient
    .post(record)
    .then(response=>{
        alert('record added')
        console.log(response);
    })
    .catch(err=>{
        console.log(err);
    });
    
    httpClient
    .get()
    .then((response)=>{
        let data = '<ul>'
        let records = JSON.parse(response);
        records.forEach(r => {
            data+= `<li>${r.firstName}.${r.lastName}</li>`
        })
        data+='</ul>'
        document.body.innerHTML += data;
        console.log(response);
    })
    .catch(err=>{
        document.write(err);
        console.log(err)
    });