I have created simple react app using 'create-react-app'. This app contains form, validation and bootstrap things. Nothing fancy yet works like a charm.
I have also signed up to mongo to get a free cluster so I can send over some data to. So I have this URL:
mongodb+srv://matt:passwprd#cluster0-jlasm.mongodb.net/test
Now, all I want to do is to send JSON data from the form to mongo but I don't know how.
When I am following tutorials and installing MongoDB, mongoose or whatever packages and adding basic setup for future CRUD operations:
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test';
// Use connect method to connect to the server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected successfully to server");
db.close();
});
The entire application crashes:
./node_modules/mongodb-core/lib/uri_parser.js
Module not found: Can't resolve 'dns' in 'C:\Users\Mateusz\Desktop\brainhub\node_modules\mongodb-core\lib'
I used to send data using jQuery or mysql_query in PHP but I can't overcome this problem. In other words I want to achieve functionality like presented in this video: https://www.youtube.com/watch?v=Jsqz5op4fH8 So as I said, simple data update.
My suspicion is that react-scripts server listener has some sort of conflict with mongo but I am not sure.
Please help me because I am loosing my nerves.
You are using node.js so start server app try using express routing here is a link to a tutorial https://zellwk.com/blog/crud-express-mongodb or https://codeburst.io/hitchhikers-guide-to-back-end-development-with-examples-3f97c70e0073 or try doing a google search(node.js mongodb and express).
Then when returning a request from server send the data required then use your react client to handle the data recived
Hope it works!
handleSubmit(){
let databody = {
"name": this.state.name,
// Remaining form Data
}
return fetch('mongodb+srv://mattOsuch:brainhub123#cluster0-jlasm.mongodb.net/test', {
method: 'POST',
body: JSON.stringify(databody),
headers: {
'Content-Type': 'application/json'
},
})
.then(res => res.json())
.then(data => console.log(data));
}
render(){
return (
<div>
<form onSubmit={this.handleSubmit}>
// Form Fields
<input type="submit" value="Save" />
</form>
</div>
);
}
To connect to MongoDb in javascript, you must use a node.js server.
It is therefore impossible to directly connect your React application to your MongoDb cluster.
For more information, visit the official MongoDb documentation
First you need to create a React.js on the frontend and then node.js on the backend web application.
Then, you need to connect your mongodb collection to your Node.js server.
Then you can send your form data to your node.js server and your node.js server will send your form data to your mongodb collection.
Making a full-stack React-NodeJS-MongoDB web application can be a little challenging, if you do not know NodeJS. So you might first start with EJS-NodeJS-MongoDB web application. But in any case, here are links for your question:
https://www.youtube.com/watch?v=3isCTSUdXaQ&t=2248s
https://www.youtube.com/watch?v=Oa0pMn0tvU4&t=1316s
Related
I'm using Using Firebase and Node.js I'm trying to make a real-time list, see code below:
router.get('/', (req, res) => {
db.ref('contacts').on('value', (snapshot) => {
const data = snapshot.val();
console.log(data);
res.render('index', { contacts: data });
});
});
but is giving me this error
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
Your code is trying to send multiple responses from an Express route. The error message is telling you that's not possible. Once you call res.render(), you are declaring the full response to be sent to the client, and that's all you can send. The client will have to make another request to get an update.
If you want to keep a socket open to the client to send updates over time, you're going to need a websocket or some other way to keep the connection open. express-ws is one thing to try on the backend. Note that this will not work with Cloud Functions and probably other serverless providers.
I'm having a hard time understanding how to connect to the MongoDB Atlas Cluster from my react-native app. What I'm trying to do is basically take my data from my component login page (userName and password) and connect to the Atlas Cluster db to see if the data is there.
Im using React Native and use Expo to create the app. My login page opens up and I put in the data.
I want to take that data and then use the following code (from the Atlas Site Connection String) to connect and check.
const MongoClient = require('mongodb').MongoClient;
const uri = "mongodb+srv://<userName>:<password>#testcluster1-dbdq3.mongodb.net/test?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("test").collection("devices");
// perform actions on the collection object
client.close();
});
Since react-native establishes a server, do I need to involve Express? Im new to this so I'm still trying to figure out what packages to utilize. Should I also install mongoose or mongoDB or both (from NPM). Im trying to wrap my head around how this works from a basic perspective and the packages required.
I want to perform a check against my userID and PW from my login page to the DB to see if the user exists. If the user doesnt, then I'll have them fill out some info and register which means writing a new user to my db.
So basically, I need to understand the code logic for:
Connecting to the db through my app and when to perform this
connection (when app loads or each time the login button is clicked)
Take data from my userName and password and search the atlas db to
see if the user exists. If so, then the next page loads.
If username and password doesn't exist, then I write the new user
and password to the db.
Thanks
I think you should rewrite the code following the format suggested by mongodb here:
https://mongodb.github.io/node-mongodb-native/api-articles/nodekoarticle1.html
So essentially:
const MongoClient = require('mongodb').MongoClient;
//make sure to check connection string is correct here, since this depends on the whether you are running standalone, replica, sharded cluster
const uri = "mongodb+srv://<userName>:<password>#testcluster1-dbdq3.mongodb.net/test?retryWrites=true&w=majority";
MongoClient.connect(uri, { useNewUrlParser: true }, function(err, client) {
if (err) {
//error
} else {
var collection = client.db('test').collection('devices');
//client.close() should be called after you are done performing actions such as collection.update, etc.
}
});
you can use any npm package with Expo if it works with RN (React Native), but you may need to detach in order to do so. Any npm packages which include native iOS or Android code will not work with Expo out of the box, unfortunately. Because MongoDB NPM package just mentioned the Node.js in thier docs, this doesn't mean that it will work on React Native. That's why MongoDB made this page about JUST React Native https://docs.mongodb.com/realm/tutorial/react-native/
You may need to use Realm Package to connect to MongoDB with React Native.
I have build a Todo App with create-react-app. The store I'm using is based on Local Storage(JS attribute of object window). Now I created a MySQL databases and want to connect to that database, so the state will show the values from database, and will be updated through actions.
I've tried to connect to db and output values through 'node' console using db.js. It works.
const mysql = require('mysql');
const con = mysql.createConnection({
host: "localhost",
user: "root",
password: "root",
database: 'root'
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM tasks", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
Is it possible to connect the state of app to database using this script?
You can't connect them directly.
JavaScript running in a web browser cannot speak the MySQL protocol (nor can it make raw network connections that would be needed to write an implementation in JS).
Instead, create a web service (in the programming language of your choice, which could be JavaScript running on Node.js (e.g. the code you have already + Express.js + some glue)) and use Ajax to communicate with it.
The general solution for a question like this is the following framework:
Back-end (Node.js, Express, Database connection including authorization)
Front-end (React(, Redux to manage state))
If you then launch the React app, it should populate its state based on data retrieved from the database, which is a process to which you can add authorization (make retrievable data depend on the role/status of the user).
In the back-end you can define functions that take in a certain subset of parameters, which performs database actions, to which you can add business rules for your application. The React app then just sends HTTP requests to the Express server, which handles everything that needs verification and authorization before even touching the data.
If you search the internet for any configuration of a fullstack architecture using React and MySQL, you'll find similar results to what I mentioned.
I'm trying to learn web programming and I don't know what I need to do.
What I'm trying to do: download data from a 3rd party website and load it into my own private SQL database.
What I've done so far: I'm working in visual studio 2017, I've got a console JavaScript project that gets the data via https request. I've also got a SQL server project working with a table ready to receive the data. I can make entries by manually doing an insert query using the visual studio interface.
What do I do next? How do I get the SQL server to listen for insert requests from an app? How do I get the data(simple arrays of numbers with no json or xml labels) from the JavaScript app to the sql server?
Once I get the JavaScript app and the server talking to eachother, can I take the next step and just have the sql server make the https requests directly?
Hoping that your are using nodejs application.
First install mssql
npm install mssql
You can try something like this.
const sql = require('mssql')
async () => {
try {
const pool = await sql.connect('mssql://username:password#localhost/database')
const result = await sql.query`insert into ... // your query`
console.dir(result)
} catch (err) {
// ... error checks
}
}
If you are not using nodejs probably any language might have basic mysql connector which you could install and start using
When you have a RESTful server which only responds with JSON by fetching some information from the database, and then you have a client-side application, such as Backbone, Ember or Angular, from which side do you test an application?
Do I need two tests - one set for back-end testing and another set for front-end testing?
The reason I ask is testing REST API by itself is kind of difficult. Consider this code example (using Mocha, Supertest, Express):
var request = require('supertest');
var should = require('chai').should();
var app = require('../app');
describe('GET /api/v1/people/:id', function() {
it('should respond with a single person instance', function(done) {
request(app)
.get('/api/v1/people/:id')
.expect(200)
.end(function(err, res) {
var json = res.body;
json.should.have.property('name');
done();
});
});
});
Notice that :id in the url? That's an ObjectId of a specific person. How do I know what to pass there? I haven't even looked into the database at this point. Does that I mean I need to import Person model, connect to database and do queries from within the tests? Maybe I should just move my entire app.js into tests? (sarcasm :P). That's a lot of coupling. Dependency on mongoose alone means I need to have MongoDB running locally in order to run this test. I looked into sinon.js, but I am not sure if it's applicable here. There weren't many examples on how to stub mongoose.
I am just curious how do people test these kinds of applications?
Have you tried using mongoose-model-stub in your server-side test? It will free you from having to remember or hardcode database info for your tests.
As for testing the client side, your "webapp" is basically two apps: a server API and a client-side frontend. You want tests for both ideally. You already know how to test your server. On the client you would test your methods using stubbed out "responses" (basically fake json strings that look like what your web service spits out) from your API. These don't have to be live urls; rather it's probably best if they're just static files that you can edit as needed.
I would use nock..https://github.com/pgte/nock
What you want to test is the code you have written for your route.
So what you do is, create a response that will be sent when the end point is hit.
Basically its a fake server..
Something like this..
Your actual method..
request({
method: "GET",
url: "http://sampleserver.com/account"
}, function(err, res, data){
if (err) {
done(err);
} else {
return done(null,data);
}
});
Then..
var nockObj = nock("http://sampleserver.com")
.get("/account")
.reply(200,mockData.arrayOfObjects);
//your assertions here..
This way you don't alter the functionality of your code.. Its like saying.. instead of hitting the live server..hit this fake server and get mock data. All you have to do is make sure your mock data is in sync with the expected data..