Universal Vue.js application with Nuxt.js part#5 Create Database API, Request data, Setup Port database and Nuxt.js Application

in #utopian-io6 years ago (edited)

Screenshot_7.png

Repository

https://github.com/nuxt/nuxt.js

What Will I Learn?

  • Create Database API
  • Request data in Nuxt.js
  • Create a database with JSON Placeholder
  • Setup Port database and Nuxt.js Application

Resources

Difficulty

Intermediated

Tutorial Contents

In this tutorial, we will learn how to use Nuxt.js to interact with our API. We will learn the Create Read Update Delete (CRUD) System on Nuxt.js. We will create the API with the help of JSON placeholder tools. I suggest you look at the basic tutorials of Nuxt.js in the curriculum section under the tutorial. because in this tutorial we will not discuss setup on Nuxt.js and handling Search engine optimization (SEO) on the server side, by using CRUD system on Nuxt.js we will see how we can interact with API without doing Request to the server. Indirectly the application that we run is a Single Page Applications (SPA), We just start to make CRUD system in Nuxt.js.

Create API with JSON-Server

I assume you have installed Nuxt.js and have created a project folder for Nuxt.js, if you have not installed and setup on Nuxt.js you can see it in my previous tutorial.I will not discuss much about the installation process of Nuxt.js, as I will focus on creating APIs locally easily including all REST APIs. I will separate the API folder with folders for clients.
Screenshot_5.png

  • Install JSON Placeholder

We will install JSON placeholder globally through NPM, we will use this tool to create a Fake API in our local server which we will use for CRUD in Nuxt.js.

NPM Install :
npm install -g json-server

After the installation process is complete you can create a file containing your database in JSON form, I have created a db.json database.

{
    "country" :[
        {
            "id" : 0,
            "name" : "Argentina",
            "city" : "Buenos aires"
        },
        {
            "id" : 1,
            "name" : "Brazil",
            "city" : "Brasília"
        },
        {
            "id" : 2,
            "name" : "Japan",
            "city" : "Tokyo"
        },
        {
            "id" : 3,
            "name" : "Germany",
            "city" : "Berlin"
        },
        {
            "id" : 4,
            "name" : "France",
            "city" : "Paris"
        }
    ]
}

to run the local server API, we can do json-server db.json, db.json is the filename of a fake database.
Noted: it is important to remember Json's key or wrapper, will be the routing or endpoint API, in the example above the key is country. So later the endpoint will be as follows http://localhost:3000/country.

Screenshot_6.png

Automatically our API server will run on localhost:3000, We need to know Nuxt.js also use the same port to run the application. We need to do the settings on the port that run Nuxt.js we can set it in package.json file. We will add config: {}.

Example:

"config": {
      "nuxt": {
        "host": "0.0.0.0",
        "port": "3333"
    }
  }



Package.json

{
  "name": "millenuxt",
  "version": "1.0.0",
  "description": "tutorial",
  "author": "millea <[email protected]>",
  "private": true,
  "config": {
      "nuxt": {
        "host": "0.0.0.0",
        "port": "3333"
    }
  },
  "scripts": {
    "dev": "nuxt",
    "build": "nuxt build",
    "start": "nuxt start",
    "generate": "nuxt generate",
    "lint": "eslint --ext .js,.vue --ignore-path .gitignore .",
    "precommit": "npm run lint"
  },
  "dependencies": {
    "axios": "^0.18.0",
    "bootstrap": "^4.1.1",
    "bulma": "^0.7.1",
    "nuxt": "^1.0.0"
  },
  "devDependencies": {
    "babel-eslint": "^8.2.1",
    "eslint": "^4.15.0",
    "eslint-friendly-formatter": "^3.0.0",
    "eslint-loader": "^1.7.1",
    "eslint-plugin-vue": "^4.0.0"
  }
}

If we run on the browser then we will see the results as follows localhost: 3000/country

tutorcrud.gif

Request to database API with Axios

We will make CRUD system using API for that we need additional library help to request to endpoint API that we make, we will use Axios.

  • Install Axios

as usual, because we will use the API we need tools to do Request to the API, we will install Axios, in our previous tutorial I have discussed the installation process and setup Axios on Nuxt.js please see for more details.
Install Axios:
npm install --save axios

then after we finish installing Axios, We will create a special file as an initialization from Axios, I will create an axios.js file in the plugins folder.

Axios.js

import axios from 'axios'
export default axios.create({
    baseURL: 'http://localhost:3000/'
});

We will create baseURL for the API we have created if you remember our API database running on localhost port:3000.

  • Request data API with Axios

We can already request and retrieve data in our API database, now we can use and display it in our Nuxt.js app
Index.vue

<template>
  <div>
    <div style="text-align: center;">
      <app-logo/>
      <h1 class="title">
        millenuxt
      </h1>
      <h2 class="subtitle">
        CRUD Nuxt.js
      </h2>
      {{countries}}
    </div>
  </div>
</template>
<script>
  import axios from "~/plugins/axios"
  import AppLogo from '~/components/AppLogo.vue'
  export default{
    components: {
      AppLogo
    },
    asyncData(){
        return axios.get('country').then(res=>({
          countries: res.data
        }))
    }
  }
</script>
  • import axios from "~/plugins/axios" We import the initialization axios we have created in axios.js, customize it with your file directory.
  • to run asynchronous data we can use the asyncData(), then we can request to API by using axios.get() for get method or axios.post() for post method. We can attach the callback function after request to get the response then(res=>({ })).
  • Then we can create a variable that we will use to save the response result from request API countries: res.data and we can extract the data like this {{countries}}.

If it does not happen error we can see the result as below, it is important to remember we must run Database server first to see the result
database server reside on port localhost: /3000 and Nuxt.js application we are on port localhost:/3333.

ezgif.com-video-to-gif.gif

We can also extract data on Html element by doing v-for on variable countries. I will extract the data that is on the country database.

Example:

<div class="alert alert-primary" role="alert" v-for="item in countries" :key="item.id">
         <p>Country : {{item.name}}</p> 
         <p>Capital City: {{item.city}}</p>
 </div>
  • We extract the data through v-for="item in countries and we must also add a :key as an indexing of the data in v-for. If there is no error then we will see the results as below and make sure the API database runs on localhost:3000 and the Nuxt.js Application runs on localhost:3333.

crud.gif

We have successfully extracted the data we retrieve from our API database located on db.json.in the next tutorial, I will make Crud System with API we have created in this tutorial. hope you enjoy this tutorial and useful for you.

Curriculum

Learn Nuxt#1 Nuxt structure, Global CSS, Request API
Learn Nuxt#2 Vuex in Nuxt.js, Classic Mode and Modules Mode
Learn Nuxt#3 Create components, Reusable components and Nuxt-link
Learn Nuxt#4 Dynamic components, Props, Transition page, Dynamic pages

Proof of Work Done

https://github.com/milleaduski/learnNuxtjs

Sort:  

Hey @duski.harahap
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Thank you for your contribution.

  • Put some comments on your code, plus the explanation you've already made.
  • Your tutorial is well explained and easy to understand. Good job!

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thanks @portugalcoin , i will do better in the next post

really helping

Congratulations @duski.harahap! You have completed the following achievement on Steemit and have been rewarded with new badge(s) :

Award for the total payout received
Award for the number of upvotes received

Click on the badge to view your Board of Honor.
If you no longer want to receive notifications, reply to this comment with the word STOP

To support your work, I also upvoted your post!

Do not miss the last post from @steemitboard:
SteemitBoard World Cup Contest - Semi Finals - Day 1


Participate in the SteemitBoard World Cup Contest!
Collect World Cup badges and win free SBD
Support the Gold Sponsors of the contest: @good-karma and @lukestokes


Do you like SteemitBoard's project? Then Vote for its witness and get one more award!

Coin Marketplace

STEEM 0.29
TRX 0.12
JST 0.033
BTC 63464.16
ETH 3111.33
USDT 1.00
SBD 3.98