从本地托管的MongoDB(Node.js)获得快速响应的问题

时间:2019-04-12 18:09:52

标签: reactjs mongodb express mongoose mern

我正尝试将数据从本地托管的MongoDB集合传递到应用程序的前端,以进行测试。

尝试让前端与后端通信时遇到麻烦。

我已经尝试过在“ getData”路由中更改参数……我想我已经转过身了。

const mongoose = require("mongoose");
const express = require("express");
var cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");

const API_PORT = 27017;
const app = express();
app.use(cors());
const router = express.Router();


const dbRoute = "mongodb://127.0.0.1:27017/nycsandy";

mongoose.connect(
  dbRoute,
  { useNewUrlParser: true }
);

let db = mongoose.connection;
let dbdata;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function () {
    db.db.collection("socialmedia", function(err, collection){
        collection.find({}).toArray(function(err, data){
            console.log("data length from coll ", data.length); // it will print the collection data just fine
            dbdata = data
        })
    });

});

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger("dev"));

// I need to get this to just return data
router.get("/getData", (req, res) => {
     return dbdata
    // I don't know what to put here to get my response?
});
.....

前端App.js如下:

// /client/App.js
import React, { Component } from "react";
import axios from "axios";

class App extends Component {
  // initialize our state
  state = {
    data: [],
    id: 0,
    message: null,
    intervalIsSet: false,
    idToDelete: null,
    idToUpdate: null,
    objectToUpdate: null
  };

  componentDidMount() {
    this.getDataFromDb();
    if (!this.state.intervalIsSet) {
      let interval = setInterval(this.getDataFromDb, 10000);
      this.setState({ intervalIsSet: interval });
    }
  }

  componentWillUnmount() {
    if (this.state.intervalIsSet) {
      clearInterval(this.state.intervalIsSet);
      this.setState({ intervalIsSet: null });
    }
  }

  getDataFromDb = () => {
    fetch("http://localhost:27017/api/getData")
        .then(data => data.text())
        .then(text => console.log(text))
// just testing it for now.
  };
......

这将引发一个空的响应错误。 ERR_EMPTY_RESPONSE

我对如何获取数据(这确实正确地登录到控制台)进入getData路由有些困惑。

谢谢。

1 个答案:

答案 0 :(得分:1)

在您的路由器中,尝试以下操作:

res.status(200).send("whatYouWantToSend")