如何将 Gatsby.js 与我的 Express 服务器链接

Enr*_*ico 7 sql ajax http node.js express

我正在尝试制作一个非常基本的全栈应用程序,其中前端是 Gatsby,后端是一个简单的 Express 服务器。我有一个数据库,其中有一些用户,目标是通过查询在后端获取这些用户,然后使用 fetch() 在 Gatsby (React) 组件中显示它们。显然出了点问题,我无法在屏幕上显示它们,即使使用 Postman 请求被正确处理。以下是相关的代码片段:

Express:我使用了经典的 express-generator,我只更改了路由文件 users.js,将其链接到数据库。(由于 Gatsby 使用端口 8000,因此无需更改端口以便 React 和 express 不会重叠)。

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;
Run Code Online (Sandbox Code Playgroud)

Gatsby 页面:这不是主要的 index.js 文件,它是页面文件夹中编码为 contacts.js 的辅助页面(Gatsby 使用内置路由方法)。该组件围绕布局(页脚和页眉,像 hbs 部分一样工作)。

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>      
    )   
  }
}
Run Code Online (Sandbox Code Playgroud)

最后,为了将后端与前端链接起来,我"proxy": "http://localhost:3000",在 Gatsby package.json 中添加了指向 Express 服务器的内容。那里一切正常,使用 Postman 以及我尝试获取数据的任何地方,但它们没有显示在屏幕上。有任何想法吗?

Sha*_*nSe 4

将其添加到您的 Gatsby-config 文件中

\n\n
module.exports = {\n  proxy: {\n    prefix: "/users",\n    url: "http://localhost:3000",\n  },\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n
\n

这样,当您在开发中 fetch(\'/users/todos\') 时,开发服务器将识别出它\xe2\x80\x99 不是静态资源,并将您的请求代理到http:// /本地主机:3000/用户/todos作为后备。

\n
\n