最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to properly connect a React js application to MongoDB database - Stack Overflow

programmeradmin1浏览0评论

I am having some problems connecting to MongoDB database. After I launch my application using npm start it will not connect to the database.

Below the code that has the problem.

The error I am getting is on the return function below:

function App() {
  return (
    <>    / <-- Error here
    <Navbar /> 
    </>
  );
}

Below the App.js code:

import React from 'react';
import './App.css';
import './GoogleMap.css';
import './ProgressBar.css';
import Home from "./pages/Home";
import Vessels from "./pages/Vessels";
import SingleVessel from "./pages/SingleVessel";
import Error from "./pages/Error";
import GoogleMap from "./pages/GoogleMap";

import {Route, Switch} from "react-router-dom";
import Navbar from "./ponents/Navbar";

const app = express();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require("body-parser");
const cors = require('cors');
const vesselsController = require("../controllers/VesselControllers");

require("../config/keys");

// DB Config
const db = require("../config/keys").MongoURI;

const options = {
    useNewUrlParser: true,
    reconnectTries: Number.MAX_VALUE,
    poolSize: 10
};

mongoose.connect(db, options)
.then(() => console.log('MongoDB Connection established'))
.catch((err) => console.log('Error connecting MongoDB database due to: ', err));

// Bodyparser
app.use(express.urlencoded({ extended: false }));

// Express Session
app.use(
    session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true
    })
);

// Routes
const PORT = process.env.PORT || 3000; // my localhost port

app.use(bodyParser.urlencoded({extended: true, limit: '50mb'}));
app.use(bodyParser.json({limit: '50mb'}));
app.use(cors());
app.route("/vessels/all").get(vesselsController.getBaseAll);
app.route("vessels/:id/track").get(vesselsController.getCurrent);
app.route("/vessels").get(vesselsController.getHistory);
app.listen(PORT, console.log(`Server started on port ${PORT}`));

function App() {
  return (
    <>
    <Navbar /> 
      <Switch>
        <Route exact path="/" ponent={Home}/>
        <Route exact path="/vessels" ponent={Vessels}/>
        <Route exact path="/vessels/:slug" ponent={SingleVessel}/>
        <Route exact path="/map" ponent={GoogleMap} />
        <Route ponent={Error} />
      </Switch>
    </>
  );
}

export default App;

What I have done so far:

1) I came across the following post but it was not totally useful to solve the error.

2) I can confirm that all necessary module have been installed and that is not an error of missing any dependency.

3) I also found this blog that helped in setting the connection but that still didn't work.

4) I can also confirm that I properly set the variables I am trying to store in the database according to the official documentation of MongoDB Schema

Thanks for pointing in the right direction for solving this problem

I am having some problems connecting to MongoDB database. After I launch my application using npm start it will not connect to the database.

Below the code that has the problem.

The error I am getting is on the return function below:

function App() {
  return (
    <>    / <-- Error here
    <Navbar /> 
    </>
  );
}

Below the App.js code:

import React from 'react';
import './App.css';
import './GoogleMap.css';
import './ProgressBar.css';
import Home from "./pages/Home";
import Vessels from "./pages/Vessels";
import SingleVessel from "./pages/SingleVessel";
import Error from "./pages/Error";
import GoogleMap from "./pages/GoogleMap";

import {Route, Switch} from "react-router-dom";
import Navbar from "./ponents/Navbar";

const app = express();
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require("body-parser");
const cors = require('cors');
const vesselsController = require("../controllers/VesselControllers");

require("../config/keys");

// DB Config
const db = require("../config/keys").MongoURI;

const options = {
    useNewUrlParser: true,
    reconnectTries: Number.MAX_VALUE,
    poolSize: 10
};

mongoose.connect(db, options)
.then(() => console.log('MongoDB Connection established'))
.catch((err) => console.log('Error connecting MongoDB database due to: ', err));

// Bodyparser
app.use(express.urlencoded({ extended: false }));

// Express Session
app.use(
    session({
        secret: 'secret',
        resave: true,
        saveUninitialized: true
    })
);

// Routes
const PORT = process.env.PORT || 3000; // my localhost port

app.use(bodyParser.urlencoded({extended: true, limit: '50mb'}));
app.use(bodyParser.json({limit: '50mb'}));
app.use(cors());
app.route("/vessels/all").get(vesselsController.getBaseAll);
app.route("vessels/:id/track").get(vesselsController.getCurrent);
app.route("/vessels").get(vesselsController.getHistory);
app.listen(PORT, console.log(`Server started on port ${PORT}`));

function App() {
  return (
    <>
    <Navbar /> 
      <Switch>
        <Route exact path="/" ponent={Home}/>
        <Route exact path="/vessels" ponent={Vessels}/>
        <Route exact path="/vessels/:slug" ponent={SingleVessel}/>
        <Route exact path="/map" ponent={GoogleMap} />
        <Route ponent={Error} />
      </Switch>
    </>
  );
}

export default App;

What I have done so far:

1) I came across the following post but it was not totally useful to solve the error.

2) I can confirm that all necessary module have been installed and that is not an error of missing any dependency.

3) I also found this blog that helped in setting the connection but that still didn't work.

4) I can also confirm that I properly set the variables I am trying to store in the database according to the official documentation of MongoDB Schema

Thanks for pointing in the right direction for solving this problem

Share Improve this question asked Feb 7, 2020 at 14:05 EmanueleEmanuele 2,4148 gold badges38 silver badges88 bronze badges 2
  • 1 React is a client side framework, you won't have access to the server directly so you can't 'connect' to MongoDB with React that way. – CoderLee Commented Feb 7, 2020 at 14:09
  • See this boilerplate for an example on how to set it up properly: github./jefelewis/react-mongodb-rest-boilerplate – nopassport1 Commented Feb 7, 2020 at 14:10
Add a ment  | 

4 Answers 4

Reset to default 4

Looks like you are trying to execute a node application into a React application, this is not possible

React works on the client side where as Node and MongoDB work on the server side. What you need to do is build or use an API that lives on the server and municates via HTTP/HTTPS messages to the client.

A React app can't do both, because it is sent to the client, the web browser, it has no way of connecting to a server outside of making request over the internet. That's why APIs are so helpful in web development. So you'll need an addition application to handle sending and receiving data via messages in HTTP.

Some resources to help you:

  • Here is a light weight tutorial for an easy introduction Medium Full Stack with Mongo and JS

  • Pluralsight's Full Stack JavaScript path and courses. They do a great job with content and will help explain a lot of concepts.

  • Alternatively LinkedIn Learning Learning has great resources as well.
  • YouTube which is a free option. Although with YouTube you may need to do more searching to find the right videos for your interest.

Hello you can use react in node as views with reactjs-express-generator

You need MongoDB Realm. There is a cool tutorial in MongoDB Website with Reactjs & GraphQL, etc...

good luck.

发布评论

评论列表(0)

  1. 暂无评论