webutvikling og api-design

 

02: Node, Fetch, basic REST, Express

How do we build a stack with JavaScript?

  1. JS outside the browser
     
  2. Build a server with it
     
  3. Use the server from the browser
     
  4. Design considerations for the server
     
  5. Use data from React

How do you use JavaScript outside a browser?

First node app

const liam = {
 name: 'Liam',
}

console.log(liam);

index.js

➜ node index.js                                                                  
{ name: 'Liam' }

Run the code with node <filename>

package.json​
{
  "name": "login-form",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^15.6.1",
    "react-dom": "^15.6.1",
    "react-scripts": "1.0.11"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "devDependencies": {
    "eslint": "^4.5.0"
  }
}
$ npm install

$ npm install --save react

$ npm install --save-dev eslint

Libs (modules)
@
./node_modules/

npm scripts

  • Give names to shell commands
     
  • Has installed modules on path
{
  "name": "f02-npm-scripts",
  "scripts": {
    "build": "concat src/**/*.js > output/script.js"
  }
}
➜ npm run build
  1. JS outside the browser
     
  2. Build a server with it
     
  3. Use the server from the browser
     
  4. Design considerations for the server
     
  5. Use data from React

How do you write a server with it?

Express

  • Easy-to-use webserver for Node

Use Express!

const express = require('express');
const app = express();

app.get(
 '/',
 (req, res) => res.send('Hello!')
);

app.listen(
 1234,
 () => console.log('Listening on port 1234!')
);
➜ node app.js                                                                                                   
Listening on port 1234!

(http://sparkjava.com/ is a fun Express-inspired Java web framework)

Serve data as JSON

// app.js

// ...

const app = express();

const greeting = {
  to: 'Liam',
  from: 'Martin',
  message: 'Hello, there!',
};

app.get('/', (req, res) => res.send(greeting));

// ...

Express defaults to JSON for objects/arrays

  1. JS outside the browser
     
  2. Build a server with it
     
  3. Use the server from the browser
     
  4. Design considerations for the server
     
  5. Use data from React

So when does it become useful?

Fetch data from server

<!-- index.html -->

<!DOCTYPE html>
<html>
<body>
  <script>
    fetch('http://localhost:1234/')
      .then(response => response.json())
      .then(greeting => document.write(greeting.message))
      .catch(err => document.write(err));
  </script>
</body>
</html>

Fetch browser compatibility

OOps: CORS

<!DOCTYPE html>
<html>
<body>
  <script>
    fetch('http://localhost:1234/')
      .then(response => response.json())
      .then(greeting => document.write(greeting.message))
      .catch(err => document.write(err));
  </script>
</body>
</html>

Cross-Origin Resource Sharing

Solution?

const cors = require('cors');
const express = require('express');

const app = express();
app.use('/', cors());
  • Use the cors package (npm <3)





     
  • … but be aware that CORS exists for a reason

bonus: Proxy

// package.json
{
  …
  "proxy": "http://localhost:1234",
  …
}

create-react-app is your friend

  1. JS outside the browser
     
  2. Build a server with it
     
  3. Use the server from the browser
     
  4. Design considerations for the server
     
  5. Use data from React

What's this "API Design"?

REST basics

  • Architectural style for sharing data on the server
     
  • Exposes "resources" via the URL
    • /users
    • /posts
    • /posts/{postId}/comments
       
  • Uses standard HTTP communication
     
  • Typically serves data (JSON or XML)—not HTML
     
  • Can be extremely simple

A way to work with data

  • Based on HTTP:
    • HTTP POST (create)
       
    • HTTP GET (read)
       
    • HTTP PUT (update)
       
    • HTTP DELETE (…)
       
    • … some more
  • Everything is a "resource"
    • <url>/users
    • <url>/users/{userId}
       
    • <url>/posts
    • <url>/users/{userId}/posts

What's an "HTTP request"?

// A GET request

GET / HTTP/1.1
Host: localhost:1234
Connection: keep-alive
Accept: */*
// Response to that request

HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: *
Content-Type: application/json; charset=utf-8
Content-Length: 55
Date: Mon, 08 Feb 2016 02:46:42 GMT
Connection: keep-alive

{"to":"Liam","from":"Martin","message":"Hello, there!"}

Takeaways

  • Literally <headers>\n\n<body>
    • Same for req AND res
       
  • The Internet is CRAZY fragile
     
  • The browser is a hero

JUST
A WAY
TO DO IT

We'll look at GraphQL later

Testing a REST api

➜ curl http://localhost:1234                                                                                                             
{"to":"Liam","from":"Martin","message":"Hello, there!"}%

cURL!

  1. JS outside the browser
     
  2. Build a server with it
     
  3. Use the server from the browser
     
  4. Design considerations for the server
     
  5. Use data from React

Bonus: Lists with React

  • Array#map!
  1. JS outside the browser
     
  2. Build a server with it
     
  3. Use the server from the browser
     
  4. Design considerations for the server
     
  5. Use data from React

Exercise 2!

  • Make a server that serves a list of something you like
     
  • Use Postman or cURL (or both!) to test it
     
  • Download the list with fetch
    • Hint: Stuff it in a component's state
       
  • Use React to display that data in the browser!

PG6300-17-02 Node, Fetch, basic REST, Express

By theneva

PG6300-17-02 Node, Fetch, basic REST, Express

Lecture 2 in PG6300-17 Web development and API design

  • 808