【问题标题】:Node.js project deployed on Heroku. Can't access API endpoints and connect with MongoDB Atlas. Returning status 404部署在 Heroku 上的 Node.js 项目。无法访问 API 端点并与 MongoDB Atlas 连接。返回状态 404
【发布时间】:2021-01-24 15:32:46
【问题描述】:

我试图找到一个与我类似的问题,我正在查看谷歌、日志并尝试整天解决这个问题,但没有任何成功。我希望你们能帮助我。

我在 Heroku 上部署了带有 Express 的 Node.js API,我正在尝试将它与 MongoDB Atlas 连接。最初在日志中是生产变量的问题,我对此进行了整理。但是,当我尝试访问任何 API 端点时,这是我得到的日志:

2021-01-23T17:49:34.346738+00:00 heroku[web.1]: Starting process with command `npm start`
2021-01-23T17:49:36.180974+00:00 app[web.1]:
2021-01-23T17:49:36.180991+00:00 app[web.1]: > eastern-beauty-backend@1.0.0 start /app
2021-01-23T17:49:36.180991+00:00 app[web.1]: > node index.js
2021-01-23T17:49:36.180991+00:00 app[web.1]:
2021-01-23T17:49:36.921969+00:00 app[web.1]: [winston] Attempt to write logs with no transports {"message":"Listening on port 31690...","level":"info"}
2021-01-23T17:49:36.926481+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string
2021-01-23T17:49:36.926482+00:00 app[web.1]: at parseConnectionString (/app/node_modules/mongodb/lib/core/uri_parser.js:565:21)
2021-01-23T17:49:36.926483+00:00 app[web.1]: at connect (/app/node_modules/mongodb/lib/operations/connect.js:282:3)
2021-01-23T17:49:36.926484+00:00 app[web.1]: at /app/node_modules/mongodb/lib/mongo_client.js:224:5
2021-01-23T17:49:36.926484+00:00 app[web.1]: at maybePromise (/app/node_modules/mongodb/lib/utils.js:665:3)
2021-01-23T17:49:36.926484+00:00 app[web.1]: at MongoClient.connect (/app/node_modules/mongodb/lib/mongo_client.js:220:10)
2021-01-23T17:49:36.926485+00:00 app[web.1]: at /app/node_modules/mongoose/lib/connection.js:833:12
2021-01-23T17:49:36.926486+00:00 app[web.1]: at new Promise (<anonymous>)
2021-01-23T17:49:36.926486+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:830:19)
2021-01-23T17:49:36.926486+00:00 app[web.1]: at /app/node_modules/mongoose/lib/index.js:345:10
2021-01-23T17:49:36.926486+00:00 app[web.1]: at /app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:31:5
2021-01-23T17:49:36.926487+00:00 app[web.1]: at new Promise (<anonymous>)
2021-01-23T17:49:36.926487+00:00 app[web.1]: at promiseOrCallback (/app/node_modules/mongoose/lib/helpers/promiseOrCallback.js:30:10)
2021-01-23T17:49:36.926487+00:00 app[web.1]: at Mongoose._promiseOrCallback (/app/node_modules/mongoose/lib/index.js:1135:10)
2021-01-23T17:49:36.926488+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:344:20)
2021-01-23T17:49:36.926488+00:00 app[web.1]: at module.exports (/app/startup/db.js:7:12)
2021-01-23T17:49:36.926488+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:9:24)
2021-01-23T17:49:36.926591+00:00 app[web.1]: (node:21) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
2021-01-23T17:49:36.926651+00:00 app[web.1]: (node:21) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
2021-01-23T17:49:37.268649+00:00 heroku[web.1]: State changed from starting to up
2021-01-23T17:49:38.509600+00:00 heroku[router]: at=info method=GET path="/" host=eastern-beauty-api.herokuapp.com request_id=d4f01cf5-9a03-43c0-b90c-502e1526d2b6 fwd="148.252.132.237" dyno=web.1 connect=0ms service=10ms status=404 bytes=415 protocol=https
2021-01-23T17:49:43.261992+00:00 heroku[router]: at=info method=GET path="/users" host=eastern-beauty-api.herokuapp.com request_id=7b2758e9-d3d9-4c5d-b693-af513424e7bd fwd="148.252.132.237" dyno=web.1 connect=0ms service=2ms status=404 bytes=420 protocol=https
2021-01-23T17:50:06.222493+00:00 heroku[router]: at=info method=GET path="/users" host=eastern-beauty-api.herokuapp.com request_id=dc17bb7f-8cb9-4e2b-ac5a-054edb95fb27 fwd="148.252.132.237" dyno=web.1 connect=0ms service=2ms status=404 bytes=420 protocol=https  

返回的状态为 404“未找到”。

它在开发模式下运行良好。我设置了与 MongoDB Atlas 连接的自定义环境变量,并在需要的地方替换了用户名、密码和 dbname。

mongodb+srv://<username>:<password>@eb.bvm0d.mongodb.net/<dbname>?retryWrites=true&w=majority

我尝试与 Shell 连接,没有任何问题。我正在考虑我的代码有什么问题,但我什么也没有发现。

这是我拥有的一些文件:

index.js

const winston = require("winston");
const express = require("express");
const config = require("config");
const app = express();


require("./startup/cors")(app);
require("./startup/routes")(app);
require("./startup/db")();
require("./startup/config")();
require("./startup/validation")();

const port = process.env.PORT || config.get("port");
const server = app.listen(port, () =>
  winston.info(`Listening on port ${port}...`)
);

module.exports = server;

startup/routes.js

const express = require('express');
const error = require('../middleware/error');
const auth = require('../routes/auth');
const users = require('../routes/users');
const customers = require('../routes/customers');
const herbs = require('../routes/herbs');
const herbsBG = require('../routes/herbsBG');
const oils = require('../routes/oils');
const oilsBG = require('../routes/oilsBG');

module.exports = function(app) {
  app.use(express.json());
  app.use('/api/auth', auth);
  app.use('/api/users', users);
  app.use('/api/customers', customers);
  app.use('/api/herbs', herbs);
  app.use('/api/herbsBG', herbsBG);
  app.use('/api/oils', oils);
  app.use('/api/oilsBG', oilsBG);
  app.use(error);
}

startup/db.js

const winston = require('winston');
const mongoose = require('mongoose');
const config = require('config');

module.exports = function() {
  const db = config.get('db');
  mongoose.connect(db, { useNewUrlParser: true })
    .then(() => winston.info(`Connected to ${db}...`));
}

config/default.json

{
  "jwtPrivateKey": "unsecureKey",
  "db": "mongodb://localhost/ebeauty",
  "port": "3900",
  "requiresAuth": false
}

config/production.json

{
  "jwtPrivateKey": "EB_jwtPrivateKey",
  "db": "eb_db"
}

在 production.json 中,我声明了自定义环境变量。变量在 Heruko,出于安全目的,这个想法是隐藏的。然后在 Heroku 上的“eb_db”下,放置与 MongoDB 连接的 URL。

感谢您的帮助!

【问题讨论】:

    标签: node.js mongodb heroku


    【解决方案1】:

    存在相关错误

    UnhandledPromiseRejectionWarning: MongoParseError: Invalid connection string

    地点是

    在 parseConnectionString (/app/node_modules/mongodb/lib/core/uri_parser.js:565:21)

    如果您使用的是最新版本的驱动程序,该代码是(来自github):

          if (parsedHost.path === '/:') {
            hostParsingError = new MongoParseError('Double colon in host identifier');
            return null;
          }
    

    这似乎意味着未转义的特殊字符或缺少环境变量。

    【讨论】:

    • 那我该怎么办?我目前唯一的成功是如果我不使用环境变量并将 mongdb atlas 连接字符串直接放在“db”下的 production.json 文件中。我知道这是不好的做法,但我正在努力找出问题所在。当我这样做时,我不会得到那么多错误。只是这个“(节点:21)DeprecationWarning:不推荐使用collection.ensureIndex。改用createIndexes。”在我的集群中,我可以看到连接,但在 API 端点获取数据仍然没有成功。我不知道还能做什么......
    • 您可以在调用 connect 之前将连接字符串打印到日志中,这样您就可以准确地看到它正在使用什么。
    猜你喜欢
    • 2020-10-17
    • 2019-12-16
    • 1970-01-01
    • 2021-08-05
    • 2020-01-05
    • 1970-01-01
    • 2021-10-17
    • 2021-08-05
    • 2021-10-02
    相关资源
    最近更新 更多