Skip to content
Advertisement

How to link Gatsby.js with my Express server

I am trying to make a very basic full-stack application where the front-end is Gatsby and the Backend is a simple Express server. I have a Database where I have some users and the goal is get these users in the backend with a query and then displaying them in the Gatsby (React) component using fetch(). Obviously something goes wrong and I cannot display them on the screen, even if using Postman the request is processed correctly. Here are the relevant code pieces:

Express: I used the classic express-generator and I only changed the route file users.js, to link it to the database. (since Gatsby uses the port 8000 there is no need in changing the port so that React and express do not overlap).

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

var mysqlconnection = mysql.createConnection({
  host     : ****,
  user     : ****,
  password : ****,
  database : ****
});

mysqlconnection.connect(function(err) {
  if (err) {
  console.log(err)
  }
  else {
  console.log(`You are now connected` )
  }
})

router.get('/', (req, res) => {
  mysqlconnection.query('SELECT * FROM table_basic', (err, rows, fields) => {
      if(!err) {
          res.send(JSON.stringify(rows, undefined, 2));
      }
      else {
          console.log(err)
      }        
  })
})



module.exports = router;

Gatsby page: this is NOT the main index.js file, it is a secondary page coded as contacts.js in the page folder (Gatsby uses a built-in routing method). The component is wrapped around the layout (footer and header, working like the hbs partials).

import React, { Component } from 'react';
import './contacts.css';
import Layout from '../components/layout';

export default class About extends Component {
    constructor(props) {
        super(props)

        this.state = {
            users: []
        }
    }


    componentDidMount() {
        fetch('/users')
          .then(res => res.json())
          .then(users => this.setState({ users }));
      }



  render() {
    return (
        <Layout>
            <h1>LISTING</h1>
            <ul>
              {this.state.users.map(user =>
                <li key={user.id}>{user.lastname}</li> 
                )}
            </ul>         
        </Layout>      
    )   
  }
}

And, finally, to link the back-end with the front-end, I added "proxy": "http://localhost:3000", in the Gatsby package.json to point to the Express server. Everything works fine there, using Postman and wherever I try to fetch the data, but they do not display on the screen. Any ideas?

Advertisement

Answer

Add this to your Gatsby-config file

module.exports = {
  proxy: {
    prefix: "/users",
    url: "http://localhost:3000",
  },
}

This way, when you fetch(‘/users/todos’) in development, the development server will recognize that it’s not a static asset, and will proxy your request to http://localhost:3000/users/todos as a fallback.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement