HMABUHABIB / udacity-front-end-nanodegree

Udacity front end nanodegree
1 stars 0 forks source link

Part 4 Web APIs and Asynchronous (Takeaway) #1

Open HMABUHABIB opened 3 years ago

HMABUHABIB commented 3 years ago

Steps to creating a local server

const port = 8000;
const server = app.listen(port, listening);
function listening(){
     console.log("server running"); 
     console.log(`running on localhost: {$port}`);
}
HMABUHABIB commented 3 years ago

New server template

/* Empty JS object to act as endpoint for all routes */
projectData = {};

// Express to run server and routes
const express = require('express');

// Start up an instance of app
const app = express();

/* Dependencies */
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());

// Cors for cross origin allowance
const cors = require('cors');
app.use(cors());

/* Initializing the main project folder */
app.use(express.static('website'));

const port = 3000;

// TODO-Spin up the server

const server = app.listen(port, listening);
function listening(){
    // console.log(server);
    console.log(`running on localhost: ${port}`);
};
HMABUHABIB commented 3 years ago
var express = require('express');
var app = express();

// respond with "hello world" when a GET request is made to the homepage
app.get('/', function (req, res) {
  res.send('hello world');
})
HMABUHABIB commented 3 years ago

Useful website

Routing JavaScript Promises: An introduction

HMABUHABIB commented 3 years ago

Client Side Code

const postData = async ( url = '', data = {})=>{
    console.log(data);
      const response = await fetch(url, {
      method: 'POST', 
      credentials: 'same-origin',
      headers: {
          'Content-Type': 'application/json',
      },
     // Body data type must match "Content-Type" header        
      body: JSON.stringify(data), 
    });

      try {
        const newData = await response.json();
        console.log(newData);
        return newData;
      }catch(error) {
      console.log("error", error);
      }
  }

postData('/add', {answer:42});
HMABUHABIB commented 3 years ago

fetch()

const postData = async ( url = '', data = {})=>{

      const response = await fetch(url, {
      method: 'POST', // *GET, POST, PUT, DELETE, etc.
      credentials: 'same-origin', 
      headers: {
          'Content-Type': 'application/json',
      },
      body: JSON.stringify(data), // body data type must match "Content-Type" header        
    });

      try {
        const newData = await response.json();
               return newData
      }catch(error) {
      console.log("error", error);
      // appropriately handle the error
      }
  }

  postData('/addMovie', {movie:' the matrix', score: 5})
HMABUHABIB commented 3 years ago

make a GET request

let baseURL = 'http://api.animalinfo.org/data/?animal='
let apiKey = '&appid=9f15e45060...';

document.getElementById('generate').addEventListener('click', performAction);

function performAction(e){
const newAnimal =  document.getElementById('animal').value;
getAnimal(baseURL,newAnimal, apiKey)

}
const getAnimal = async (baseURL, animal, key)=>{

  const res = await fetch(baseURL+animal+key)
  try {

    const data = await res.json();
    console.log(data)
    return data;
  }  catch(error) {
    console.log("error", error);
    // appropriately handle the error
  }
}
HMABUHABIB commented 3 years ago

Wait for a Function to Finish in JavaScript

doFirstThing()
.then(result => doSecondThing(result))
.then(newResult => doThirdThing(newResult))
.then(finalResult => {
  console.log("The final result thing"+finalResult);
})
.catch(failureCallbackfunction);
}
HMABUHABIB commented 3 years ago

Project links

openweathermap conditions Fetch the Weather with OpenWeatherMap API and JavaScript

HMABUHABIB commented 3 years ago
body.cloudy {
  background-image: linear-gradient(
    to right top,
    #63747c,
    #71858e,
    #7f96a0,
    #8da8b2,
    #9bbac5
  );
}
body.rainy {
  background-image: linear-gradient(
    to right top,
    #637c7b,
    #718e8c,
    #7ea09e,
    #8db2b0,
    #9bc5c3
  );

document.body.className = 'sunny';