【问题标题】:Can't retrieve information from mongodb when deploying on heroku在heroku上部署时无法从mongodb检索信息
【发布时间】:2021-05-13 17:36:30
【问题描述】:

问题正如标题所暗示的那样。当我在本地运行我的应用程序时,我能够从 MongoDB 检索信息,但在 Heroku 上,返回 undefined。我是否应该以另一种方式连接到 MongoDB,因为如果我对一些文本进行硬编码,一切都会正常工作。这是我的脚本:

获取数据的函数

const MongoClient = require("mongodb").MongoClient;
const dbConnectionUrl = "mongodb+srv://xxxxxxx@cluster0.ro4dz.mongodb.net/data?retryWrites=true&w=majority";

const saySomething = (req, res, next) => {
    // res.status(200).json({
    //     body: 'Hello from the server!'
    // });
    login()
    .then(val=>res.send(val))
};

async function login(){
    const client = new MongoClient(dbConnectionUrl)
    try{
        await client.connect();
        const database = client.db("data");
        const movies = database.collection("movies");
        const query = { name: "toke" };
        const movie = await movies.findOne(query);
        return movie
    }catch(err){
        console.log(err)
    }
}

module.exports.saySomething = saySomething;

路由器

const express = require('express');
const router = express.Router();
const controllers = require('./../controllers/controllers');


router.get('/say-something', controllers.saySomething);

module.exports = router;

服务器

// Import dependencies
const express = require('express');
const cors = require('cors');
const path = require('path');

// Create a new express application named 'app'
const app = express();

// Set our backend port to be either an environment variable or port 5000
const port = process.env.PORT || 5000;

// This application level middleware prints incoming requests to the servers console, useful to see incoming requests
app.use((req, res, next) => {
    console.log(`Request_Endpoint: ${req.method} ${req.url}`);
    next();
});

// Configure the CORs middleware
// Require Route

app.use(cors());
const api = require('./routes/routes');
// Configure app to use route
app.use('/api', api);

// This middleware informs the express application to serve our compiled React files
if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'staging') {
    app.use(express.static(path.join(__dirname, 'client/build')));

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

// Catch any bad requests
app.get('*', (req, res) => {
    res.status(200).json({
        msg: 'Catch All'
    });
});

// Configure our server to listen on the port defiend by our port variable
app.listen(port, () => console.log(`BACK_END_SERVICE_PORT: ${port}`));

正面

import { useEffect, useState } from 'react';
import './App.css';
import axios from 'axios'


function App(){
  useEffect(()=>{
    get()
  })
  const[text, settext] = useState('')
  async function get(){
    let request = await axios.get('/api/say-something')
    console.log(request.data.name)
    settext(request.data.name)
  }
  return(
    <div>{text}</div>
  )
}

export default App;

【问题讨论】:

    标签: node.js mongodb heroku


    【解决方案1】:

    我解决了这个问题!我做的第一件事是通过 Heroku 在我的应用程序中添加 MongoDB 连接 URI 作为环境变量。其次,我在 MongoDB 中添加了一个选项,以便可以从任何计算机访问集群。默认情况下,访问设置为本地计算机,因此我在集群中添加了另一个 IP,即 0.0.0.0/0,现在一切正常。

    【讨论】:

      猜你喜欢
      • 2019-11-19
      • 2020-01-05
      • 2020-07-11
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-01
      • 2022-08-14
      • 1970-01-01
      相关资源
      最近更新 更多