Подключение к Airtable с использованием API и Node.js - PullRequest
0 голосов
/ 29 января 2019

Я пытаюсь подключиться к своей базе Airtable с помощью API, но он не будет отображать элементы.

Я разместил весь свой код минус мой фактический ключ API и базовый идентификатор, если мне не хватает нескольких файловно я не вижу, что я делаю неправильно, какие-либо идеи?

Вот скриншот того, что я получаю.

enter image description here

Вот мой HTML-код

    <!DOCTYPE html>
    <html>
      <head>
        <title>Airtable Furniture Gallery</title>
        <meta name="description" content="Rendering Airtable data in a web page">
        <link id="favicon" rel="icon" href="https://glitch.com/favicon.ico" type="image/x-icon">
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="/style.css">
      </head>
      <body>
        <header>
          <h1>
            Furniture Gallery
          </h1>
          ⚡️ Powered by <a href="https://airtable.com" target="_blank">Airtable</a>!
          Fetches data from <a href="https://airtable.com/shrS8HlgVQE7mJbfB" target="_blank">this base.</a>
        </header>

        <main id="data-container">
          Loading...
        </main>

        <script src="https://button.glitch.me/button.js" data-style="glitch"></script>
        <div class="glitchButton" style="position:fixed;top:20px;right:20px;"></div>

        <!-- Your web-app is https, so your scripts need to be too -->
        <script src="https://code.jquery.com/jquery-2.2.1.min.js"
                integrity="sha256-gvQgAFzTH6trSrAWoH1iPo9Xc96QxSZ3feW6kem+O00="
                crossorigin="anonymous"></script>
        <script src="/client.js"></script>

      </body>
    </html>

Вот мой файл client.js

    // client-side js
    // run by the browser each time your view template is loaded

    $(function() {
      $.getJSON('/data', function(data) {
        var $dataContainer = $('#data-container');

        if (data.error) {
          $dataContainer.html('Error! ' + data.error);
          return;
        }

        // Clear the loading message.
        $dataContainer.html('');

        data.records.forEach(function(record) {
          var $galleryCard = $('<div class="gallery-card" />');
          if (record.picture[0]) {
            // Just show the first picture, if it has one.
            $('<img />').attr('src', record.picture[0].url).appendTo($galleryCard);
          }
          var $label = $('<strong />').text(record.name);
          $galleryCard.append($label);
          $dataContainer.append($galleryCard);
        });
      });
    });

Вот файл package.json

    {
        "name": "airtable-example",
        "version": "0.0.1",
        "description": "Display data from an Airtable base",
        "main": "server.js",
        "scripts": {
            "start": "node server.js"
        },
        "dependencies": {
        "express": "^4.12.4",
        "airtable": "0.5.0"
        },
        "engines": {
            "node": "6.9.x"
        },
        "keywords": [
            "node",
            "express",
            "airtable"
        ],
        "license": "MIT"
    }

Вот мойserver.js

    // server.js
    // where your node app starts

    // We're going to use the "Product Catalog and Orders" base template:
    // https://airtable.com/templates/featured/expZvMLT9L6c4yeBX/product-catalog-and-orders
    var Airtable = require('airtable');
    var base = new Airtable({
      apiKey: process.env.AIRTABLE_API_KEY,
    }).base(process.env.AIRTABLE_BASE_ID);
    var tableName = 'Furniture';
    var viewName = 'Main View';

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

    // http://expressjs.com/en/starter/static-files.html
    app.use(express.static('public'));

    // http://expressjs.com/en/starter/basic-routing.html
    app.get("/", function(request, response) {
      response.sendFile(__dirname + '/views/index.html');
    });

    // Cache the records in case we get a lot of traffic.
    // Otherwise, we'll hit Airtable's rate limit.
    var cacheTimeoutMs = 5 * 1000; // Cache for 5 seconds.
    var cachedResponse = null;
    var cachedResponseDate = null;

    app.get("/data", function(_, response) {
      if (cachedResponse && new Date() - cachedResponseDate < cacheTimeoutMs) {
        response.send(cachedResponse);
      } else {
        // Select the first 10 records from the view.
        base(tableName).select({
          maxRecords: 10,
          view: viewName,
        }).firstPage(function(error, records) {
          if (error) {
            response.send({error: error});
          } else {
            cachedResponse = {
              records: records.map(record => {
                return {
                  name: record.get('Name'),
                  picture: record.get('Picture'),
                };
              }),
            };
            cachedResponseDate = new Date();

            response.send(cachedResponse);
          }
        });
      }
    });

    // listen for requests :)
    var listener = app.listen(process.env.PORT, function() {
      console.log('Your app is listening on port ' + listener.address().port);
    });

Вот мой style.css

    /* styles */
    /* called by your view template */

    * {
      box-sizing: border-box;
    }

    body {
      font-family: helvetica, arial, sans-serif;
      margin: 25px;
    }

    h1 {
      font-weight: bold;
      font-size: 48px;
      color: Indigo;
      margin-bottom: 0;
    }

    header {
      margin-bottom: 2em;
    }

    footer {
      margin-top: 50px;
      padding-top: 25px;
      border-top: 1px solid lightgrey;
    }

    footer > a {
      color: #BBBBBB;
    }

    main {
      display: flex;
      flex-wrap: wrap;
    }

    .gallery-card {
      min-height: 160px;
      width: 200px;

      border: 1px solid #777;
      border-radius: 5px;
      box-shadow: 2px 2px 0 2px rgba(0,0,0,0.2);
      padding: 0.5em;
      margin-left: 1em;
      margin-bottom: 1em;
    }

    .gallery-card img {
      border-radius: 5px;
      margin-bottom: 0.5em;
      width: 100%;
    }

Вот мой файл .env

    # Environment Config

    # store your secrets and config variables in here
    # only invited collaborators will be able to see your .env

    # reference these in your code with process.env.CONFIG

    # Your Airtable API key. It'll look like key123asdf123asdf
    AIRTABLE_API_KEY=key123asdf123asdf

    # Your Airtable base ID. It'll look like app123asdf123asdf
    AIRTABLE_BASE_ID=app123asdf123asdf

    # note: .env is a shell file so there can't be spaces around '=
...