【问题标题】:How to make a node.js api and deploy it to heroku (postgresql or mySQL database)如何制作 node.js api 并将其部署到 heroku(postgresql 或 mySQL 数据库)
【发布时间】:2021-05-30 11:27:28
【问题描述】:

我正在使用 node.js 和 express 开发连接到客户端的 rest api 我在这里找到了一个教程 https://www.taniarascia.com/node-express-postgresql-heroku/ 并且一切正常,但它不会部署到 heroku 我不知道为什么,因为一切正常当我在本地主机上运行它时很好。为什么会这样?

这是我的代码

index.js

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const {pool} = require("./config");
const { get } = require("mongoose");
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(cors());
const getBooks = (req, res) => {
    pool.query('SELECT * FROM books', (err, results) => {
        if(err){
            throw err;
        }
        res.status(200).json(results.rows);
    });
}
const addBook = (req, res) => {
    const {author, title} = req.body;
    pool.query(
        'INSERT INTO books (author, title) VALUES ($1, $2)',
        [author, title],
        (err) => {
            if(err){
                throw err;
            }
            res.status(201).json({status: "success", message: "Book added."});
        },
    )
}

app.route("/books").get(getBooks).post(addBook);
app.listen(process.env.PORT || 8000, () => {
    console.log(`Server listening`);
})

config.js

require("dotenv").config();
const {Pool} = require("pg");
const isProduction = process.env.NODE_ENV === "production";
const connectionString = `postgresql://${process.env.DB_USER}:${process.env.DB_PASSWORD}@${process.env.DB_HOST}:${process.env.DB_PORT}/${process.env.DB_DATABASE}`;
const pool = new Pool({
    connectionString: isProduction ? process.env.DATABASE_URL : connectionString,
    ssl: isProduction,
});
module.exports = {pool};

init.sql

CREATE TABLE books (
    ID SERIAL PRIMARY KEY,
    author VARCHAR(255) NOT NULL,
    title VARCHAR(255) NOT NULL
);

INSERT INTO books (author, title)
VALUES ('J.K. Rowling', 'Harry Potter');

【问题讨论】:

  • 能否将heroku logs 的输出添加到问题中?

标签: mysql node.js postgresql api heroku


【解决方案1】:

我会看看这个,如果您的应用程序在本地运行良好但在 heroku 上运行良好,则可能是部署问题: https://devcenter.heroku.com/articles/getting-started-with-nodejs

具体来说,我认为您可能需要一个 Procfile,它就像 Heroku 需要部署的额外文件。假设您已使用 cli (https://devcenter.heroku.com/categories/command-line) 进行设置,您可以通过在您部署的文件夹中使用“heroku logs -t”获取日志来获取有关您的应用程序如何失败的更多详细信息。

【讨论】:

    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 2019-05-31
    • 2013-06-23
    • 2021-06-12
    • 2018-12-13
    • 2017-11-03
    • 1970-01-01
    • 2021-03-23
    相关资源
    最近更新 更多