为什么我的具有节点和mysql后端的react应用程序在本地运行,但不能在Heroku上运行?

时间:2019-01-17 16:33:06

标签: mysql node.js reactjs heroku

初始请求的起始路由为“ http://localhost:5000/contacts”。部署到heroku之后,呈现了UI,但是没有数据,并且我的状态为404:找不到。显示的网址就是这个网址:“ https://powerful-gorge-20271.herokuapp.com/contacts”。我在heroku上使用Clear-DB add作为mySql数据库。我尝试将react应用程序的package.json文件中的代理从“ http://localhost:5000”修改为heroku url,但这不起作用。此应用的存储库为:https://github.com/aosante/React-Contact-Manager

我以这篇文章https://daveceddia.com/deploy-react-express-app-heroku/作为指导,但仍然无法正常工作

这是app.js文件中的代码

const express = require('express');
const cors = require('cors');
const mysql = require('mysql');
const path = require('path');

const port = process.env.PORT || 4000;
const app = express();

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

//production mode
if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, 'client/build')));
  app.get('*', (req, res) => {
    res.sendfile(path.join((__dirname, 'client/build', 'index.html')));
  });
}

app.use(cors());

const SELECT_ALL_CONTACTS = `SELECT * FROM contacts ORDER BY firstName ASC`;

//Connection creation to mysql database
const connection = mysql.createConnection({
  host: 'host goes here',
  user: 'user goes here',
  port: 'goes here',
  password: 'password goes here',
  database: 'heroku_cdf7d751774d818',
  insecureAuth: true
});



 connection.connect(err => {
  if (err) console.log(err);
});

//Server start
app.listen(port, () => {
  console.log('Server started on port ' + port);
});

app.get('/api', (req, res) => {
  connection.query(SELECT_ALL_CONTACTS, (err, results) => {
    if (err) {
      res.send(err);
    } else {
      return res.json({
        data: results
      });
    }
  });
});

app.get('/api/contacts', (req, res) => {
  connection.query(SELECT_ALL_CONTACTS, (err, results) => {
    if (err) {
      res.send(err);
    } else {
      return res.json({
        data: results
      });
    }
  });
});

app.post('/api/contacts/add', (req, res) => {
  const { firstName, lastName, email, phone } = req.query;
  const INSERT_CONTACT = `INSERT INTO contacts (firstName, lastName, email, phone) VALUES ('${firstName}', '${lastName}', '${email}', '${phone}')`;
  connection.query(INSERT_CONTACT, (err, results) => {
    if (err) {
      console.log(err);
    } else {
      return res.send(results);
    }
  });
});

app.delete('/api/contacts/delete/:id', (req, res) => {
  const { id } = req.params;
  const DELETE_CONTACT = `DELETE FROM contacts WHERE id = ${id}`;
  connection.query(DELETE_CONTACT, (err, results) => {
    if (err) {
      console.log(err);
    } else {
      return res.send(results);
    }
  });
});

app.get('/api/contacts/edit/:id', (req, res) => {
  const { id } = req.params;
  const GET_CONTACT = `SELECT * FROM contacts WHERE id = ${id}`;
  connection.query(GET_CONTACT, (err, results) => {
    if (err) {
      res.send(err);
    } else {
      return res.json({
        data: results
      });
    }
  });
});

app.put('/api/contacts/update/:id', (req, res) => {
  const { id } = req.params;
  const { firstName, lastName, email, phone } = req.query;
  const UPDATE_CONTACT = `UPDATE contacts SET firstName = '${firstName}', lastName = '${lastName}', email = '${email}', phone = '${phone}' WHERE id = ${id}`;
  connection.query(UPDATE_CONTACT, (err, results) => {
    if (err) {
      console.log(err);
    } else {
      res.send(results);
    }
  });
});

//production mode
if (process.env.NODE_ENV === 'production') {
  app.use(express.static(path.join(__dirname, 'client/build')));
  app.get('*', (req, res) => {
    res.sendFile(path.join((__dirname, 'client/build', 'index.html')));
  });
}

//this goes in the end after all the requests
//build mode
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname + '/client/public/index.html'));
});

这就是package.json文件中的内容:

{
  "name": "react-contact-manager",
  "version": "1.0.0",
  "description": "Simple contact manager with mysql backend",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon app.js",
    "client-install": "npm install --prefix client",
    "client": "npm start --prefix client",
    "dev": "concurrently \"npm run server\" \"npm run client\"",
    "heroku-postbuild": "npm install --prefix client && npm run build - -prefix client"
  },
  "keywords": [
    "react",
    "mysql"
  ],
  "author": "Andrés Osante",
  "license": "ISC",
  "dependencies": {
    "concurrently": "^4.1.0",
    "cors": "^2.8.5",
    "express": "^4.16.4",
    "mysql": "^2.16.0",
    "nodemon": "^1.18.9"
  }
}

我还添加了一个Procfile,上面写有“ web:node app.js”,但这无济于事

1 个答案:

答案 0 :(得分:0)

几件事。路线的顺序在Express中很重要-先到先得。

由于在生产中,您捕获了所有路由app.get('*',以服务于前端,因此其他路由将永远不会被击中。声明其他路线后,您需要将其移至app.js的结尾。

此外,您应该仔细定义您的路线,以使前端和后端之间不会发生碰撞。我不确定您是否使用React Router,但是您在应用程序的根目录('/'上定义了一条获取路由。这将与您的前端冲突。这似乎与/contacts的作用相同,所以继续删除根定义。

我个人不确定,也许其他人可以添加,但是在您的package.json的{​​{1}}中,请考虑重新定义scripts。我不确定更改目录可能会对应用程序造成什么影响,也许什么也没做。但是,这是另一种处理方式:

heroku-postbuild