简体   繁体   English

将 node.js express 后端部署到 heroku

[英]Deploy node.js express backend to heroku

Its my first time deploying on heroku and i keep getting errors, the build is succeeding but when the build finishes and i try to view the API response in the browser via heroku i get back an error of -这是我第一次在 heroku 上部署并且我不断收到错误,构建成功但是当构建完成时,我尝试通过 heroku 在浏览器中查看 API 响应我得到一个错误
Failed to load resource: the server responded with a status of 500 (Internal Server Error)加载资源失败:服务器响应状态为 500(内部服务器错误)

logs from heroku -来自 heroku 的日志 -
2021-12-11T19:16:54.702260+00:00 app[web.1]: npm ERR! 2021-12-11T19:16:54.702260+00:00 应用程序 [web.1]:npm 错误! errno 1错误号 1
2021-12-11T19:16:54.708322+00:00 app[web.1]: npm ERR. 2021-12-11T19:16:54.708322+00:00 应用程序 [web.1]:npm 错误。 example-create-react-app-express@1.0:0 start: node server.js example-create-react-app-express@1.0:0 开始: node server.js
2021-12-11T19:16:54.708419+00:00 app[web.1]: npm ERR! 2021-12-11T19:16:54.708419+00:00 应用程序 [web.1]:npm 错误! Exit status 1退出状态 1
2021-12-11T19:16:54.708524+00:00 app[web.1]: npm ERR! 2021-12-11T19:16:54.708524+00:00 应用程序 [web.1]:npm 错误!
2021-12-11T19:16:54.708602+00:00 app[web.1]: npm ERR. 2021-12-11T19:16:54.708602+00:00 应用程序 [web.1]:npm 错误。 Failed at the example-create-react-app-express@1.0.0 start script.在 example-create-react-app-express@1.0.0 启动脚本中失败。
2021-12-11T19:16:54.708721+00:00 app[web.1]: npm ERR. 2021-12-11T19:16:54.708721+00:00 应用程序 [web.1]:npm 错误。 This is probably not a problem with npm.这可能不是 npm 的问题。 There is likely additional logging output above.上面可能还有额外的日志记录 output。
2021-12-11T19:16:54.718471+00:00 app[web.1]: 2021-12-11T19:16:54.718471+00:00 应用 [web.1]:
2021-12-11T19:16:54.719294+00:00 app[web.1]: npm ERR: A complete log of this run can be found in: 2021-12-11T19:16:54.719294+00:00 app[web.1]: npm ERR:此运行的完整日志可在以下位置找到:
2021-12-11T19:16:54.719298+00:00 app[web.1]: npm ERR. 2021-12-11T19:16:54.719298+00:00 应用程序 [web.1]:npm 错误。 /app/.npm/_logs/2021-12-11T19_16_54_709Z-debug.log /app/.npm/_logs/2021-12-11T19_16_54_709Z-debug.log
2021-12-11T19:16:54.908600+00:00 heroku[web.1]: Process exited with status 1 2021-12-11T19:16:54.908600+00:00 heroku[web.1]:进程以状态 1 退出
2021-12-11T19:16:55.067169+00:00 heroku[web.1]: State changed from starting to crashed 2021-12-11T19:16:55.067169+00:00 heroku[web.1]: State 从开始变为崩溃
2021-12-11T19:16:56.373561+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/api/hello" host=agile-spire-07157.herokuapp.com request_id=ab0c71fb-1be1-4829-b123-e57cc4e7fafd fwd="67.177.196.118" dyno= connect= service= status=503 bytes= protocol=https 2021-12-11T19:16:56.373561+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/api/hello" host=agile-spire-07157.herokuapp .com request_id=ab0c71fb-1be1-4829-b123-e57cc4e7fafd fwd="67.177.196.118" dyno= connect= service= status=503 bytes= protocol=https
2021-12-11T19:17:56.820732+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=agile-spire-07157.herokuapp.com request_id=b9615ee7-190d-44ce-8d97-c099d26149ca fwd="67.177.196.118" dyno= connect= service= status=503 bytes= protocol=https 2021-12-11T19:17:56.820732+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=agile-spire-07157.herokuapp.com request_id =b9615ee7-190d-44ce-8d97-c099d26149ca fwd="67.177.196.118" 测功机=连接=服务=状态=503字节=协议=https

Any help at all is greatly appreciated非常感谢任何帮助

Folder structure:文件夹结构:
在此处输入图像描述

server.js: server.js:

const express = require('express');
const axios = require('axios');
require('dotenv').config();
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());

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

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

const port = process.env.PORT || 2000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const apiKey = process.env.APIKEY

app.get('/api/hello', (req, res) => {
    const { term, location } = req.query
    const config = {
        method: 'get',
        url: `https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}`,
        headers: {
            'Authorization': `Bearer ${apiKey}`
        }
    };

    axios(config)
        .then(function (response) {
            return JSON.stringify(response.data, null, 2)
        })
        .then(function (jsonResponse) {
            res.send(jsonResponse)
        })
        .catch(function (error) {
            console.log(error);
        });
});

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

package.json for server: package.json 用于服务器:

{
  "name": "example-create-react-app-express",
  "version": "1.0.0",
  "scripts": {
    "start": "node server.js",
    "client": "cd ../client && yarn start",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
  },
  "engines": {
    "node": "14.17.3"
  },
  "dependencies": {
    "axios": "^0.24.0",
    "body-parser": "^1.18.3",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "concurrently": "^4.0.1"
  }
}

So i think i figured it out, it seems to be working and heres what i changed:所以我想我想通了,它似乎正在工作,这就是我改变的地方:
I added a Procfile in the root directory (make sure its a capital P) and added this to it -> web: node server.js我在根目录中添加了一个 Procfile(确保它是大写的 P)并将其添加到它 -> web: node server.js
(so just put web: node(whatever your server file is named) (所以只需输入 web: 节点(无论您的服务器文件名为什么)

If you are storing your API key in a.env file then you have to let heroku know youre doing just that.如果您将 API 密钥存储在 a.env 文件中,那么您必须让 heroku 知道您正在这样做。 You can let heroku know this by typing this command in terminal while in server folder您可以通过在服务器文件夹中的终端中键入此命令来让 heroku 知道这一点
heroku config:set <key=value> heroku 配置:设置 <key=value>
If you did this right youll get back a response from heroku saying just that.如果你做对了,你会得到 heroku 的回复,就是这么说的。

This is a link i followed instructions with that worked for me这是我按照说明操作的链接,对我有用
https://dzone.com/articles/deploy-your-node-express-app-on-heroku-in-8-easy-s https://dzone.com/articles/deploy-your-node-express-app-on-heroku-in-8-easy-s

Final server.js最终 server.js

const express = require('express');
const axios = require('axios');
require('dotenv').config();
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
app.use(cors());
const port = process.env.PORT || 2000;

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const apiKey = process.env.APIKEY

app.get('/api/hello', (req, res) => {
    const { term, location } = req.query
    const config = {
        method: 'get',
        url: `https://api.yelp.com/v3/businesses/search?term=${term}&location=${location}`,
        headers: {
            'Authorization': `Bearer ${apiKey}`
        }
    };

    axios(config)
        .then(function (response) {
            return JSON.stringify(response.data, null, 2)
        })
        .then(function (jsonResponse) {
            res.send(jsonResponse)
        })
        .catch(function (error) {
            console.log(error);
        });
});

app.listen(process.env.PORT || 2000, () => console.log(`Listening on port ${port}`))

Package.json for server: Package.json 用于服务器:

{
  "name": "example-create-react-app-express",
  "version": "1.0.0",
  "engines": {
    "node": "14.17.3"
  },
  "scripts": {
    "start": "node server.js",
    "client": "cd ../client && yarn start",
    "server": "nodemon server.js",
    "dev": "concurrently --kill-others-on-fail \"yarn server\" \"yarn client\""
  },
  "dependencies": {
    "axios": "^0.24.0",
    "body-parser": "^1.18.3",
    "cors": "^2.8.5",
    "dotenv": "^10.0.0",
    "express": "^4.17.1"
  },
  "devDependencies": {
    "concurrently": "^4.0.1"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM