0

I have been playing with React for days now and while I like the frontend aspects of it, I am having a considerable time getting a mongodb backend to work and am still unable to get my form data posted onto mongodb. I've read through many tutorials and I need some help as to why I can't just ajax request onto mongo.

Here are the tutorials I've attempted to follow along:

And I have posted my problem before (twice) How to post data to mongodb from a contact form

I didn't receive an answer but the following comment on it helped me along. Here is the comment.

instead of using form method, use ajax, like fetch for instance, and send a POST request to your express route

The general consensus around the answer, and comments from my previous question direct me towards the youtube video tutorial. That is what I've been trying to do but I can't get it to work due to a number of errors. (I'll list below). The tutorials also don't help too much because they are pretty much too different to implement.

As to the actual code, here is my src/modules/contact.js file:

import React, { Component } from 'react';
import Formsy from 'formsy-react';
import { FormsyText } from 'formsy-material-ui/lib';
import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import Snackbar from 'material-ui/Snackbar';
import '../assets/css/style.css';

class ContactForm extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = { open: false };
  }

  handleSubmit(data) {

     #########PROBLEM#########
     .....how am I suppose to use .fetch to an express route
           and post to mongo here?...................
     ##########################
  }

  handleTouchTap = () => {
    this.setState({ open: true });
  }

  handleRequestClose = () => {
    this.setState({ open: false });
  }

  render() {
    return(
      <div>
        <Paper className="Form" zDepth={2}>
          <Formsy.Form onSubmit={this.handleSubmit} >
            <FormsyText
              required
              name="name"
              floatingLabelText="Enter your name"
            />
            <FormsyText required name="email"
              floatingLabelText="Enter your email address"
            />
            <FormsyText
              required
              name="message"
              floatingLabelText="What can I do for you?"
            />
            <RaisedButton onTouchTap={this.handleTouchTap}
               type="submit"
               label="Submit your message"
               primary={true}
            />
            <Snackbar
              open={this.state.open}
              message="Thank your for submitting your message. I'll get back to you as soon as I can!"
              autoHideDuration={2000}
              onRequestClose={this.handleRequestClose}
            />
          </Formsy.Form>
        </Paper>
      </div>
    );

Here is my src/modules/mongo.js file:

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const ObjectId = require('mongodb').ObjectID;
const url = 'mongodb://localhost:27017/danielrubio';

const insertFormData(db, callback) {
   db.collection('contactsubmissions').insertOne( {
      "name": 'Daniel Rubio',
      "message": 'message for you',
      "email": 'abcd@gmail.com'
    }, function(err, result) {
    assert.equal(err, null);
    console.log("Inserted a document into the contact submissions collection.");
    callback();
  });
};

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  insertDocument(db, function() {
    db.close();
  });
});

My question is how exactly do I get my mongo.js file to talk to my contact.js file?

In mongo.js I have placed at the top of the file:

var express = require('express')
var app = express()

......code......

export { app };

Then in contact.js when I import app to use the fetch ajax method I get this error when the server starts:

Error in ./~/require_optional/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/drubio/Desktop/react_personal_website/node_modules/require_optional
 @ ./~/require_optional/index.js 2:7-20

Error in ./~/send/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/drubio/Desktop/react_personal_website/node_modules/send
 @ ./~/send/index.js 24:9-22

Error in ./~/resolve-from/index.js
Module not found: Error: Cannot resolve module 'module' in /Users/drubio/Desktop/react_personal_website/node_modules/resolve-from
 @ ./~/resolve-from/index.js 3:13-30

Error in ./~/mime/mime.js
Module not found: Error: Cannot resolve module 'fs' in /Users/drubio/Desktop/react_personal_website/node_modules/mime
 @ ./~/mime/mime.js 2:9-22

Error in ./~/destroy/index.js
Module not found: Error: Cannot resolve module 'fs' in /Users/drubio/Desktop/react_personal_website/node_modules/destroy
 @ ./~/destroy/index.js 14:17-30

How am I supposed to make the post request to mongo if I can't import the express route onto my contact.js file? I really don't want to start from scratch again and if I can get a concrete example or a resource to a github repo that implements this I would really appreciate it. Everything I've tried so far just doesn't work.

If I am not supposed to do it this way and make a $.ajax request, then how do I specify the parameters to in the $.ajax call to insert in my mongo database?

Community
  • 1
  • 1
Dan Rubio
  • 4,709
  • 10
  • 49
  • 106
  • 1
    you seem to be mixing up the backend with the frontend... like what are you doing with express? do you have a route that you post to? – aw04 Nov 28 '16 at 16:05
  • Thanks for the quick response @aw04. I am using express as illustrated in this youtube video to connect to my mongo database and post to it. https://www.youtube.com/watch?v=ZKwrOXl5TDI That's what I was told to research and implement. Can you elaborate what you mean by "mixing my backend and frontend". To me it's clear what I am trying to do, I am simply trying to establish a connection to mongo when the submit form is clicked. I want to post to `mongodb://localhost:27017/danielrubio` as the url but when I try to do that with express it gives me a bunch of weird errors like the ones in the ? – Dan Rubio Nov 28 '16 at 16:10
  • Or I guess let me phrase it another way. If I am mixing the back and front end, is there a clear cut way of separating them. Perhaps a github repository, a tutorial that is up to date and standardized, documentation somewhere as an example? – Dan Rubio Nov 28 '16 at 16:12
  • so express runs on node, which is your backend server and completely independent of your react app... so for instance you should not be importing anything to do with express or mongodb into your react code – aw04 Nov 28 '16 at 16:35
  • what i think you're missing is the express part. notice in the tutorial where he defines the app.get and app.post functions, these provide routes that you can post to from your front end, and that should be the only communication between the two. in other words, there is no direct communication between react and mongo, only between react and express and express and mongo – aw04 Nov 28 '16 at 16:36
  • as for resources, i would suggest you do a node/express tutorial – aw04 Nov 28 '16 at 16:37
  • and regarding the last part, again, you don't post to mongodb, you post to your express route and that takes care of mongo (per the tutorial you linked, which is also what id do for what its worth) – aw04 Nov 28 '16 at 16:38
  • also, the first (scotch.io) tutorial you linked is about universal javascript, which is a different concept and beyond the scope of what you're doing, and the second on react router is about client side routing, and seemingly unrelated as well – aw04 Nov 28 '16 at 16:45

0 Answers0