Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 731
Enrico Avatar asked Nov 05 '18 18:11

Enrico


2 Answers

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.

like image 159
ShaLinSe Avatar answered Oct 16 '22 15:10

ShaLinSe


In development you need to add to your gatsby-config.js the proxy-middleware as others have said. In production will be totally dependent on where you are running/hosting the Gatsby project. Is your project self-hosted? It depends on what HTTP web server you are running. Nginx for example: you need to open the Nginx configuration file and create a block that allows calls to find your express server on port 3000 (http://nginx.org/en/docs/beginners_guide.html)

location /api {
proxy_set_header 'Access-Control-Allow-Origin' 'http://xxx.xxx';
proxy_set_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
proxy_set_header 'Access-Control-Allow-Headers' 'X-Requested-With,Accept,Content-Type,Origin';

proxy_pass http://127.0.0.1:3000;
proxy_redirect off;
proxy_buffering on;

proxy_set_header    Host                        $host;
proxy_set_header    X-Real-IP               $remote_addr;
proxy_set_header    X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header    origin                  `http://xxx.xxx';}

This example is from https://www.rodrigoplp.com/blog/using-your-own-server-with-gatsby

like image 1
Lumens Avatar answered Oct 16 '22 17:10

Lumens