Workspace
  • Study Book
  • WEB Network HTTP etc
    • Performance Optimization
    • Performance Optimization
    • HTTP/2 & SPDY
    • WebSocket
    • HTTP Header
    • Cross-Origin Resource Sharing
    • JSON, XML, other format
  • Javascript
    • Promise
    • make API call
    • Web API
    • Common JS
    • AJAX
    • Event DOM and delegation
    • ES6 new features
    • special function
    • function API
  • React
    • class component
    • Example
    • Lifting functions/ state up
    • Hot Loader
    • Testing
    • New Features
    • Hook
    • Simple code
    • Life Cycle
  • CSS
    • Horizontal & Vertical Align
    • GPU Animation
    • transform-function
    • LVHA Pseudo-classes
    • Selector
    • How To CSS
  • HTML
  • Redux
  • NodeJS
    • File System
  • express
    • express questions
    • express mongodb
  • Restful API
  • MongoDB
  • Compare
  • Test
    • Jest
  • Deploy development
  • coding question
  • DevOps
  • Webpack
  • GraphQL
Powered by GitBook
On this page
  • How to make HTTP request
  • Fetch
  • Fetching data from the server
  • AJAX
  • Axios

Was this helpful?

  1. Javascript

make API call

How to make HTTP request

  • AJAX

  • jQuery

  • Fetch

  • Axios

Fetch

A Fetch API provides a fetch method defined on a window object, which you can use to perform requests and sent it to the server. This method returns a Promise that you can use to retrieve the response of the request.

fetch('https://api.mydomain.com').
then(response => response.json()).
then(data => this.setState({ data }));

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(myJson);
  });

Fetching data from the server

fetch("/add", {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify({
            a: parseInt(a),
            b: parseInt(b)
        })
    })
    .then(res => res.json())
    .then(data => {
        const {
            result
        } = data;
        document.querySelector(
            ".result"
        ).innerText = `The sum is: ${result}`;
    })
    .catch(err => console.log(err));
// Some code
export async function getAllUsers() {

    try{
        const response = await fetch('/api/users');
        return await response.json();
    }catch(error) {
        return [];
    }
    
}

export async function createUser(data) {
    const response = await fetch(`/api/user`, {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({user: data})
      })
    return await response.json();
}

AJAX

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

Axios

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  
  
const axios = require('axios');

export async function getAllUsers() {

    try{
        const response = await axios.get('/api/users');
        console.log('response  ', response)
        return response.data;
    }catch(error) {
        return [];
    }
    
}

export async function createUser(data) {
    const response = await axios.post(`/api/user`, {user: data});
    return response.data;
}

PreviousPromiseNextWeb API

Last updated 2 years ago

Was this helpful?

A basic web app data flow architecture