首页 > 解决方案 > 将 React + Node.js 应用程序部署到 Heroku 并收到无法 GET / 错误?

问题描述

我一直在与另一位开发人员合作,我们已经能够使用 Express 将 React + Node.js 应用程序部署到 Heroku,但是我们仍然收到如下屏幕截图所示的错误。

截屏

我显然从服务器收到了 404,我觉得我们已经接近解决问题了;我们只是不知道它是一个简单的语法修复还是一般的结构。

这是我的根 package.json 文件:

{
  "name": "dev-personal-portfolio-2",
  "version": "1.0.0",
  "description": "",
  "main": "server.js",
  "scripts": {
    "start": "node server.js",
    "server": "nodemon index.js",
    "test": "echo \"Error: no test specified \" && exit 1",
    "post-build": "cd client && npm i && npm run build"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@sendgrid/mail": "^7.2.1",
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "nodemon": "^2.0.4"
  }
}

这是 server.js 文件:

require ('dotenv').config();

const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const buildPath = ('build/index.html');
const port = process.env.PORT || 5000;

const sendGrid = require('@sendgrid/mail');
const server = express();
server.use(bodyParser.json());

server.use(cors());

// server.use((req, res, next) => {
//   res.setHeader('Access-Control-Allow-Origin', '*');
//   res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE');
//   res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
//   next();
// });

// server.get('/api', (req, res, next) => {
//   res.send('API Status: Running')
// });


server.use(express.static('client/build'));
// server.use('/static', express.static('public'))
// server.use(express.static(path.resolve(__dirname, './public')));

// server.get('*', (req, res) => {
//     res.sendFile(path.resolve(__dirname, 'index.html'));
// });
console.log(express.static('client/build'));
console.log(`${__dirname}/public/index.html`);
server.use(express.json());

const REACT_APP_SENDGRID_API_KEY =`${process.env.REACT_APP_SENDGRID_API_KEY}`
server.post('/api/email', (req, res, next) => {
  sendGrid.setApiKey(REACT_APP_SENDGRID_API_KEY);
  console.log(req.body);
  const msg = {
      to: 'kevgill95@gmail.com',
      from: req.body.email,
      subject: req.body.subject,
      text: req.body.message
  }

  sendGrid.send(msg)
      .then(result => {
          res.status(200).json({
            success: true
          });

      })
      .catch(err => {
          console.log('error: ', err);
          res.status(401).json({
            success: false
          })
      })
});

server.listen(port, () => {
  console.log(`Server is up on port ${port}!`);
});

注意:对于 console.logs,以下是它们返回的内容:

console.log(express.static('client/build'));
[功能:服务静态]

控制台.log( ${__dirname}/public/index.html); /Users/kevingillooly/dev-personal-portfolio-2/public/index.html

我们也尝试注释掉代码行以尝试解决问题,但我们没有遇到任何可行的方法。

如果有人知道问题出在哪里,那就太棒了。构建成功了,但是问题很模糊,我们尝试了很多不同的方法。

标签: javascriptreactjsherokudeployment

解决方案


推荐阅读