Node.js

[Node.js] Make API Server (template: Pokemon)

brightlightkim 2022. 3. 20. 02:54

Making the API Server in JavaScript File

var express = require('express');
var router = express.Router();

//First Building API

/* GET home page. */
router.get('/', function(req, res) {
  res.sendFile('index.html', { root: 'public' });
});

router.get('/pokemon', function(req, res) {
  res.send(pokemon);
});

var pokemon = [
  {
    name: 'Pikachu',
    avatarUrl: 'https://assets.pokemon.com/assets/cms2/img/pokedex/full/025.png'
  },
  {
    name: 'Charmander',
    avatarUrl: 'http://24.media.tumblr.com/tumblr_ma0tijLFPg1rfjowdo1_500.gif'

  },
  {
    name: 'Mew',
    avatarUrl: 'http://media3.giphy.com/media/J5JrPT8r1xGda/giphy.gif'
  },
  {
    name: 'Cubone',
    avatarUrl: 'https://assets.pokemon.com/assets/cms2/img/pokedex/full/104.png'
  },
  {
    name: 'Cleffa',
    avatarUrl: 'http://media1.giphy.com/media/pTh2K2xTJ1nag/giphy.gif'
  },
  {
    name: 'Gengar',
    avatarUrl: 'https://s-media-cache-ak0.pinimg.com/originals/7e/3b/67/7e3b67c53469cc4302035be70a7f2d60.gif'
  }
];

module.exports = router;

 

How to use this server? >> Vue.js (app.js)

/*global Vue */
var app = new Vue({
  el: '#app',
  data: {
    pokis: [],
    pokiName: '',
    pokiURL: '',
  },
  created: function() {
    this.getpokis();
  },
  methods: {
    async getpokis() {
      // `this` points to the vm instance
      console.log("get pokis");
      var url = "http://localhost:8080/pokemon";
      try {
        let response = await axios.get(url);
        this.pokis = response.data;
        console.log(this.pokis);
        return true;
      }
      catch (error) {
        console.log(error);
      }
    },
  }
});

So Basically, 

await axios.get(url)

url includes the part of /pokemon.
And the server only gets the router route to match it andget the data.

 

How to display it in index.html?

<body>
  <div id="app">
    <div v-if='!pokis.length' class='no-pokemon center stretch'>
      <h1 class='h1'>
        Set up your endpoint at `/pokemon` to get this view working
      </h1>
    </div>
    <div v-else>
      <ul>
        <li v-for="item in pokis">
          <h1>{{ item.name }}</h1>
          <img class='avatar' v-bind:src="item.avatarUrl" />
        </li>
      </ul>
    </div>
  </div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js" integrity="sha256-mpnrJ5DpEZZkwkE1ZgkEQQJW/46CSEh/STrZKOB/qoM=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.2/dist/vue.js"></script>
  <script src="javascripts/app.js"></script>
</body>

'Node.js' 카테고리의 다른 글

[Node.js] npm run lint -- --fix  (0) 2022.04.05
[Node.js] Fetch, REST, using Asynchronous Calls  (0) 2022.03.20
[Node.js] Front End - Axios Library(Vue CLi)  (0) 2022.03.19
Node.js Express Back-end REST API  (0) 2022.03.19
Node.js Stream & Buffers  (0) 2022.03.19