AlnurFaisal / learn-fetch

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Learn Fetch

Official fetch docs

Getting started

  • set up client

    • Fork and clone repo
    • Install dependencies: yarn install (node-fetch is the only dependency)
    • cd learn-fetch
  • start server

    • [Skip if you've alr done this] git clone https://github.com/thoughtworks-jumpstart/express_passport_mongoose_example.git
    • cd express_passport_mongoose_example
    • yarn inlstall
    • mongod
    • yarn start (this will run on port 3000)

Writing our HTTP requests using fetch

GET requests

GET /api/public

fetch(`${BASE_URL}/api/public`)
  .then(data => data.json())
  .then(data => console.log(data));

POST requests with options (HTTP method)

POST /api/users

fetch(`${BASE_URL}/api/users",`{
  method: "POST"
})
  .then(data => data.json())
  .then(data => console.log(data));

POST requests with options (HTTP method + headers + body)

POST /api/users (create new user)

fetch(`${BASE_URL}/api/users",`{
  method: "POST",
  headers: {
    "Accept": "application/json",
    "Content-Type": "application/json"
  },
  body: JSON.stringify({
    user: {
      username: "someuser",
      email: "someuser@email.com",
      password: "12345678"
    }
  })
})
  .then(data => data.json())
  .then(data => console.log(data));

Any request with authorization token

GET /api/users (protected route)

fetch(`${BASE_URL}/api/user",`{
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
    Authorization:
      "Token <YOUR_TOKEN_HERE>"
  }
})
  .then(data => data.json())
  .then(data => console.log(data));

About


Languages

Language:JavaScript 100.0%