【问题标题】:Unable to GET data from Heroku Postgres into React app through Express无法通过 Express 从 Heroku Postgres 获取数据到 React 应用程序
【发布时间】:2019-07-20 16:13:08
【问题描述】:

我正在 Heroku 上建立一个由 React 和 Heroku Postgres 和 Express 组成的测试网站,以将两者结合在一起。在 componentDidMount() 上,React 部分通过 Express 发出两个 fetch() 请求。第一个返回一个 response.send(),第二个连接到 Heroku Postgres 应用程序,我设置该应用程序以提取一系列书名以呈现到列表中。 Heroku 没有 GET-ing 我请求的数据,而是返回了以下控制台消息:

请求失败 SyntaxError: Unexpected token 503(服务不可用)

我相信第一个错误消息与第一个 fetch() 请求有关,第二个错误消息与第二个 fetch() 请求有关。然而,React 应用程序确实加载了。

在尝试连接之前,我使用以下命令将数据推送到此 Heroku 应用的 Heroku Postgres:

cat db/data.sql | heroku pg:psql -a testapp

并检查发现我推送的数据在数据库中。

我正在使用 Heroku recommended approach 在 index.js 中使用 Client 而不是 Pool。 一些 stackoverflow 频道建议使用 setting DATABASE_URL 来修复与 Heroku Postgres 的 Express 连接。我使用 Heroku CLI 的尝试返回了“无法覆盖附件值 DATABASE_URL”

这是网站每个部分的代码,以及它们的 package.json 文件。我按以下顺序组织了我的文件:

  • /root(包含所有文件,包括 index.js 和支持 index.js 的 package.json 文件)

  • /root/db(包含处理 Heroku Postgres GET 请求的 query.js 和 index.js)

  • /root/client(包含来自 create-react-app 的文件)

/root/package.json

{
  "name": "testapp",
  "main": "index.js",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.0.0",
    "express": "^4.17.1",
    "express-promise-router": "^3.0.3",
    "path": "^0.12.7",
    "pg": "^7.11.0"
  },
  "engines":{
    "npm": "6.4.1",
    "node": "10.15.3"
  },
  "scripts": {
    "start": "node index.js",
    "test": "echo \"Error: no test specified\" && exit 1",
    "heroku-postbuild": "npm install && cd client && npm install && npm run build"
  },
  "license": "ISC"
}

/root/index.js

const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const path = require('path');
const port = process.env.PORT || 5000; 

const db = require('./db/queries.js')

app.use(bodyParser.json())

app.use(express.static(path.join(__dirname, 'client/build'))); 

app.get("/", async (request, response) => {
  if (error) {
    throw error
  }
  response.send("Server running on Node.js, Express, and Postgres API")
})

app.get("/NewArrivals", db.getNewArrivals)

app.get('*', (req, res) => {  
  res.sendFile(path.join(__dirname+'/client/public/index.html'));
})

app.listen(port, () => {
    console.log(`App running on port ${port}.`)
})

/root/.env

PGHOST=localhost
PGUSER=me
PGDATABASE=booklibrary
PGPASSWORD=x
PGPORT=5432

/root/db/queries.js

const { Pool, Client } = require('pg')
const connectionString = process.env.DATABSE_URL; 
const client = new Client({
    connectionString: connectionString,
    ssl:true,
})

require('dotenv').config();
client.connect()

const getNewArrivals = (request, response) => {
    client.query('SELECT * FROM newarrival ORDER BY id ASC', (error, results) 
    => {
        if (error) {
            throw error
        }
        response.status(200).json(results.rows)
        client.end();
    })
}

module.exports = {
    getNewArrivals

/root/client 文件夹的内容与 create-react-app 的输出完全相同。 App.js 例外,我修改如下:

import React from 'react';
import { useEffect, useState } from 'react';
import logo from './logo.svg';
import './App.css';

function App(props) {
  let [cards, setCards] = useState([])

  //Runs on ComponentDidMount() 
  useEffect(() => {
      //Obtains data from PostgreSQL db for renderData
      fetch('/', {method:"GET"})
          //Here I call 2 promise functions: The first fetches data 
          (response), the second examines text in response (data)
          .then(function(response){
              return response.json()
              //Examines data in response
              .then(function(data){
                  console.log(data)
              })
          }).catch(function(error){
              console.log('Request failed', error)
          })   

      //Obtains data from Heroku Postgres db for renderData
      fetch('/NewArrivals', {method:"GET"})
          .then(function(response){
              return response.json()
              //Examines data in response
              .then(function(data){
                  console.log(data)
                  renderData(data)
              })
          }).catch(function(error){
              console.log('Request failed', error)
          })  
       }, []); 

  //Generates list of book titles
  const renderData = (data) => { 
    cards.splice(0, cards.length);
    let newCards = [];
    newCards.splice(0, newCards.length);

    for(let i=0; i<4; i++){
      let card = [
        <div key={`card.${i}`} style={{width: '100%', height: 'auto', 
        border:'1px solid white'}}>
            {data[i].title}
        </div>
      ]
      newCards = [...newCards, ...card]
    }
      setCards([...newCards]) 
  }
  return (
    <div className="App">
      <header className="App-header">
        <div>
          Titles available:
          {cards}
        </div>
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

我确定我在让 Heroku Postgres 与 Express 对话时遗漏了一些东西。提前致谢。

【问题讨论】:

  • 你读过这个answer了吗,这是一个可能的修复无法覆盖附件值DATABASE_URL
  • 是的,也试过了。我销毁了数据库,使用 Heroku 控制台构建了一个新数据库,并停止更改 DATABSE_URL。必须有一种方法可以按原样连接到 Heroku Postgres 数据库。也许它会自动生成一些我必须在我的 index.js 文件中定位的 .env 文件?
  • 我很佩服您仍在尝试通过命令行执行此操作,但是为了跳过它带来的复杂性,您为什么不尝试在线 Heroku 仪表板?

标签: reactjs express heroku


【解决方案1】:

更新:这个来自 Heroku 的更新教程成功了: https://devcenter.heroku.com/articles/getting-started-with-nodejs#provision-a-database

对于那些寻找示例实现的人,请查看我在此处所做的操作: https://github.com/YFLooi/marketsurveyapp/blob/master/web/server.js https://github.com/YFLooi/marketsurveyapp/blob/master/web/db/queries.js


在尝试完成这项工作一段时间后,我决定将我的 PostgreSQL 数据库托管在外部站点上。与 Heroku Postgres 不同,ElephantSQL 提供了使用我项目的 .env 文件中的 DATABASE_URL 连接到数据库的难度较低的选项。我设法将我的 Heroku 应用程序连接到它,结果如下(加载时弹出的表格):

https://github.com/YFLooi/test4heroku

感谢本教程向我展示了绳索:

https://www.fullstackagile.eu/2017/06/04/js-sql-fullstack-guide/

【讨论】:

    猜你喜欢
    • 2021-05-22
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多