【问题标题】:How to link Gatsby.js with my Express server如何将 Gatsby.js 与我的 Express 服务器链接
【发布时间】:2019-04-09 03:10:59
【问题描述】:

我正在尝试制作一个非常基本的全栈应用程序,其中前端是 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;

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>      
    )   
  }
}

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

【问题讨论】:

    标签: sql node.js ajax http express


    【解决方案1】:

    我遇到了同样的问题,并按照 GatsbyJS 网站上“高级代理”下的建议解决了这个问题:

    https://www.gatsbyjs.org/docs/api-proxy/#advanced-proxying

    我对您的建议是您将 gatsby-config.js不是 package.json)文件修改为以下内容:

    var proxy = require("http-proxy-middleware")
    
    module.exports = {
      developMiddleware: app => {
        app.use(
          proxy({
            target: "http://localhost:3000",
          })
        )
      },
    }
    

    您可能需要创建 gatsby-config.js 文件。您可能还需要从 package.json 文件中删除“代理”行。

    【讨论】:

      【解决方案2】:

      将此添加到您的 Gatsby 配置文件中

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

      这样,当你在开发中 fetch('/users/todos') 时,开发 服务器将识别出它不是静态资产,并将代理 您对http://localhost:3000/users/todos 的请求作为后备。

      【讨论】:

      • 这仅适用于gatsby develop,对吧?关于在产品构建中代理的任何建议?
      【解决方案3】:

      在开发中,您需要像其他人所说的那样将代理中间件添加到您的 gatsby-config.js 中。在生产中将完全取决于您在哪里运行/托管 Gatsby 项目。 您的项目是自托管的吗?这取决于您正在运行的 HTTP Web 服务器。以 Nginx 为例:您需要打开 Nginx 配置文件并创建一个块,允许调用在端口 3000 (http://nginx.org/en/docs/beginners_guide.html) 上找到您的 express 服务器

      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';}
      

      这个例子来自https://www.rodrigoplp.com/blog/using-your-own-server-with-gatsby

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-08
        • 2021-11-02
        • 2021-09-21
        • 1970-01-01
        • 2021-11-19
        相关资源
        最近更新 更多