02: Node, Fetch, basic REST, Express
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 eslintLibs (modules)
@
./node_modules/
{
"name": "f02-npm-scripts",
"scripts": {
"build": "concat src/**/*.js > output/script.js"
}
}
➜ npm run buildconst 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)
// 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
<!-- 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>
<!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
const cors = require('cors');
const express = require('express');
const app = express();
app.use('/', cors());
// package.json
{
…
"proxy": "http://localhost:1234",
…
}create-react-app is your friend
// 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!"}We'll look at GraphQL later
➜ curl http://localhost:1234
{"to":"Liam","from":"Martin","message":"Hello, there!"}%cURL!