Я пытаюсь развернуть Heroku и получаю эту ошибку — code = H10, desc = метод сбоя приложения = ПОЛУЧИТЬ путь =»/» status = 503

#javascript #node.js #mongodb #heroku #npm

#javascript #node.js #mongodb #heroku #npm

Вопрос:

Я пытаюсь развернуть Heroku и получаю следующую ошибку. Я также добавил правильный скрипт в package.json, а также web: node app.js в Procfile. Я не уверен, что происходит не так. Любая помощь будет оценена.

 2020-11-13T00:08:36.927175 00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-11-13T00:08:36.937119 00:00 app[web.1]: 
2020-11-13T00:08:36.937376 00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-11-13T00:08:36.937493 00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-11-13T00_08_36_928Z-debug.log
2020-11-13T00:08:37.022916 00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:08:37.099623 00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:08:37.103557 00:00 heroku[web.1]: State changed from crashed to starting
2020-11-13T00:08:40.893537 00:00 heroku[web.1]: Starting process with command `npm start`
2020-11-13T00:08:46.434145 00:00 app[web.1]: 
2020-11-13T00:08:46.434159 00:00 app[web.1]: > NotesAppGIT@1.0.0 start /app
2020-11-13T00:08:46.434159 00:00 app[web.1]: > node app.js
2020-11-13T00:08:46.434160 00:00 app[web.1]: 
2020-11-13T00:09:17.069358 00:00 app[web.1]: Unable to connect to database
2020-11-13T00:09:17.091792 00:00 app[web.1]: npm ERR! code ELIFECYCLE
2020-11-13T00:09:17.092287 00:00 app[web.1]: npm ERR! errno 1
2020-11-13T00:09:17.111324 00:00 app[web.1]: npm ERR! NotesAppGIT@1.0.0 start: `node app.js`
2020-11-13T00:09:17.111442 00:00 app[web.1]: npm ERR! Exit status 1
2020-11-13T00:09:17.111634 00:00 app[web.1]: npm ERR!
2020-11-13T00:09:17.111801 00:00 app[web.1]: npm ERR! Failed at the NotesAppGIT@1.0.0 start script.
2020-11-13T00:09:17.111949 00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2020-11-13T00:09:17.121499 00:00 app[web.1]: 
2020-11-13T00:09:17.131690 00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2020-11-13T00:09:17.131692 00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2020-11-13T00_09_17_112Z-debug.log
2020-11-13T00:09:17.214878 00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:09:17.254440 00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:09:18.344634 00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=notes-app-tanmay.herokuapp.com request_id=d05a7b5f-6e9b-46a5-9c32-65a8850ca8d8 fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:09:18.406623 00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=notes-app-tanmay.herokuapp.com request_id=5313647a-7b67-498d-a6b3-609a8a99e33c fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:10:54.105165 00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/getNotes" host=notes-app-tanmay.herokuapp.com request_id=5249c422-c8d0-4024-b15a-bb7d46cd0eb9 fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:20:05.000000 00:00 app[api]: Build started by user t.kulkarni@student.fontys.nl
2020-11-13T00:20:14.000000 00:00 app[api]: Build failed -- check your build output: https://dashboard.heroku.com/apps/234008c5-0108-4501-8638-a536a6f392bc/activity/builds/68ca6bf4-5b07-4d64-b751-29189c2271cc
2020-11-13T00:21:56.000000 00:00 app[api]: Build started by user t.kulkarni@student.fontys.nl
2020-11-13T00:22:21.550005 00:00 app[api]: Deploy f854e773 by user t.kulkarni@student.fontys.nl
2020-11-13T00:22:21.550005 00:00 app[api]: Release v7 created by user t.kulkarni@student.fontys.nl
2020-11-13T00:22:22.544958 00:00 heroku[web.1]: State changed from crashed to starting
2020-11-13T00:22:26.000000 00:00 app[api]: Build succeeded
2020-11-13T00:22:26.340735 00:00 heroku[web.1]: Starting process with command `node app.js`
2020-11-13T00:22:58.765046 00:00 app[web.1]: Unable to connect to database
2020-11-13T00:22:58.831915 00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:22:58.903673 00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:22:58.907147 00:00 heroku[web.1]: State changed from crashed to starting
2020-11-13T00:23:02.186041 00:00 heroku[web.1]: Starting process with command `node app.js`
2020-11-13T00:23:34.617141 00:00 app[web.1]: Unable to connect to database
2020-11-13T00:23:34.674900 00:00 heroku[web.1]: Process exited with status 1
2020-11-13T00:23:34.746652 00:00 heroku[web.1]: State changed from starting to crashed
2020-11-13T00:23:35.188323 00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=notes-app-tanmay.herokuapp.com request_id=616fd65b-5fd6-492e-b221-e1131b9cbff8 fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
2020-11-13T00:23:38.591573 00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/getNotes" host=notes-app-tanmay.herokuapp.com request_id=c708048e-b554-4f1f-856b-dc27f8f9318f fwd="81.173.75.97" dyno= connect= service= status=503 bytes= protocol=https
  

Ниже приведен мой db.js файл

 // Import MongoDB Drivers

const MongoClient = require("mongodb").MongoClient; // Initialize mongodb to required MongoClient
const ObjectID = require('mongodb').ObjectID; // Initialize mongodb to required ObjectID
const dbname = "NotesAppGIT"; // State the DB name as "crud_mongodb"
const url = "mongodb://localhost:27017"; // Specify the location of mongoDB on local
const mongoOptions = {useNewUrlParser : true, useUnifiedTopology: true}; // Set flags for NewUrlParser amp; UnifiedTopology as true and pass them as MongoOptions

// Create connection between NodeJS amp; MongoDB Server

// State the initial default state as null
const state =
    {
        db : null
    };

// Connect Method

const connect = (cb) => // pass call back
{
    if(state.db) // If there is a database connection, call the callback function
    {
        cb();
    }
    else // If there is no database connection use the MongoClient to connect to the database
    {
        MongoClient.connect(url,mongoOptions,(err,client)=> // Use MongoClient to connect to the database
        {
            if(err) // If there are errors pass it through the call back function
            {
                cb(err);
            }
            else // If there are no errors set the state of the database and call the call back function
            {
                state.db = client.db(dbname);
                cb();
            }
        });
    }
}

// Primary Key Function

const getPrimaryKey = (_id) => // pass the id of the document
{
    return ObjectID(_id); // Return the ObjectID along with it's ID. This will be used to query the database by ID
}

// Get DB Method

const getDB = ()=> // return the state of the database
{
    return state.db;
}

module.exports = {getDB, connect, getPrimaryKey}; // Pass all the functions though module.exports
  

Ниже приведен мой app.js файл

 // Import modules as variables

const express = require('express'); // Required for routing
const bodyParser = require("body-parser"); // Required to pass JSON data between Client Side amp; Server Side
const app = express(); // Create instance of express application
app.use(bodyParser.json()); // State the express application to use the body-parser module and parse JSON data through it
const path = require('path'); // Required to serve a static HTML file

const db = require("./db"); // Initialize db as required db path
const collection = "notes"; // Initialize name of the collections as "notes"

// GET Routes

// Send a static HTML file to the user

app.get('/', (req, res) => // Root get path amp; pass response amp; request object
{
    res.sendFile(path.join(__dirname, 'index.html')); // Send a static HTML file from the path module
});

// Query the database for all the notes from the notes collection and return them to the user

app.get('/getNotes', (req, res) => // getNotes path amp; pass response amp; request object
{
    db.getDB().collection(collection).find({}).toArray((err, documents) => // Call the getDB method (Line #51 od db.js file) amp; pass the name of the collection.Call the method find to have all the documents from the Notes collection.
    {
        if (err) // If there is an error, print an error in the console for the user
        {
            console.log(err);
        } else // If there is no error, print the documents returned form the server and get the response of the documents in JSON format
        {
            res.json(documents);
        }
    });
});


// UPDATE Routes

// Pass a route parameter. The id is the primary key of the document needed to update. Pass the request amp; response function

app.put('/:id', (req, res) => {
    const notesID = req.params.id; // get the ID of the notes
    const userInput = req.body; // get the input of the notes from the user. User's data will be in the form of JSON

    // Connect to the database and called the notes collection. Call a function findOneAndUpdate and pass the first argument as query object hence pass find by ID amp; notes. Pass the document for update, Pass the options and set returnOriginal to false. Pass the call back and pass error and result

    db.getDB().collection(collection).findOneAndUpdate({_id: db.getPrimaryKey(notesID)}, {$set: {notes: userInput.notes}}, {returnOriginal: false}, (err, result) => {
        if (err) // If there is an error, print an error in the console for the user
        {
            console.log(err);
        } else // If there is no error then display the result as a response in JSON format
        {
            res.json(result);
        }
    });
});

// CREATE Route

app.post('/', (req, res) => {
    const userInput = req.body;
    db.getDB().collection(collection).insertOne(userInput, (err, result) => {
        if (err)
            console.log(err);
        else {
            res.json({result: result, document: result.ops[0]});
        }
    });
});


// DELETE Route

app.delete('/:id', (req, res) => {
    const notesID = req.params.id;

    db.getDB().collection(collection).findOneAndDelete({_id: db.getPrimaryKey(notesID)}, (err, result) => {
        if (err) {
            console.log(err);
        } else {
            res.json(result);
        }
    });
});

// Connect to the database [line #19 of db.js file]

db.connect((err) => // Pass a callback
{
    if (err) // If there is an error in connecting to the database print "Unable to connect to database" in the console and terminate the application
    {
        console.log('Unable to connect to database');
        process.exit(1);
    } else // If a database connection is successful, listen on port 3000 and print "connected to database, app listening on port 3000" in the console
    {
        app.listen(process.env.PORT || 3000, () => {
            console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
        });
    }
})
  

Ниже приведен мой файл package.json

 {
  "name": "NotesAppGIT",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "mongodb": "^3.6.2",
    "node": "^15.0.1",
    "path": "^0.12.7"
  }
}
  

Я не уверен, почему это происходит. Любая помощь будет очень признательна. Спасибо

Скриншот ошибки —

введите описание изображения здесь

Комментарии:

1. есть 2 журнала ошибок, которые вы должны проверить. посмотрите на последний скриншот

2. Действительно ли mongod запущен на порту 27017?

Ответ №1:

Похоже, что есть проблема с Database URL . Попробуйте заменить его URL-адресом рабочей базы данных.

db.js файл

 const url = "mongodb://localhost:27017"; // change this to production URL