You are on page 1of 35

MONGO DB CONNECTION

By using Mongoose we’re able to access the MongoDB database in an object-oriented way.
This means that we need to add a Mongoose schema
MongoDB's collections, by default, do not require their documents to have the same
schema. That is:
•The documents in a single collection do not need to have the same set of fields and the data
type for a field can differ across documents within a collection.
•To change the structure of the documents in a collection, such as add new fields, remove
existing fields, or change the field values to a new type, update the documents to the new
structure.
This flexibility facilitates the mapping of documents to an entity or an object. Each
document can match the data fields of the represented entity, even if the document has
substantial variation from other documents in the collection.
QUERYING THE DATABASE
app.get("/show", app.get('/:id', function(req, res)
function(req,res) { {
Contact.find(function(err, let id = req.params.id;
contacts) { Contact.findById(id,
function(err, contact) {
if (err) { res.json(contact);
console.log(err); });
});
} else {
res.json(contacts);
}
});
});
https://medium.com/codingthesmartway-com-blog/the-mern-stack-tutorial-
building-a-react-crud-application-from-start-to-finish-part-2-637f337e5d61
STORING FORM DATA WITH MULTIPLE FIELDS
app.post("/contact", function (req, res) {
console.log(req.body.email);
contact = new Contact(req.body);
const contact = new Contact({
email: req.body.email,
query: req.body.query,
});
contact.save(function (err) {
if (err) {
throw err;
} else {
res.render("contact");
}
});
REACT
REACT
MULTI-PAGE VIEW
SPA
❑Instead, modern apps tend to adhere to what is known as a Single-page app (SPA) model.
❑This is a world where you never navigate to different pages or ever even reload a page.
❑Instead, the different views of your app are loaded and unloaded into the same page itself.
ISSUES

❑In a single-page application, the bulk of your time will be spent keeping your
data in sync with your UI.
❑Which elements do we keep on the page, and which do we destroy?
❑Manipulating the DOM is really REALLY slow.
❑Manipulating the DOM is the primary way you are able to respond to user
actions and display new content
❑Working with HTML templates can be a pain
❑ templates might be unintelligible, with a boatload of custom
tags designed to help map your HTML elements to some
data
REACT
❑Automatic UI State Management
❑With single-page apps, keeping track of your UI and maintaining state is hard—and very time-
consuming. With React, you need to worry only about one thing: the final state your UI is in.
❑Lightning-fast DOM Manipulation
❑It does so by comparing the changes between your virtual DOM and the real DOM, figuring out which
changes actually matter, and making the least amount of DOM changes needed to keep everything up-
to-date in a process called reconciliation.
❑APIs to Create Truly Composable Uis
❑Instead of treating the visual elements in your app as one monolithic chunk, React encourages you to
break your visual elements into smaller and smaller components.
❑React extends that well-established idea to how we should think about user interfaces as well. Many of
React’s core APIs make it easier to create smaller visual components that can later be combined with
other visual components to make larger and more complex visual components

https://codingthesmartway.com/the-mern-stack-tutorial-building-a-react-crud-application-from-start-to-finish-part-1/
REACT
❑Visuals Defined Entirely in JavaScript
❑Templating frameworks vary widely
❑In React, by having your UI defined entirely in JavaScript, you get to use all of the rich functionality
JavaScript provides for doing all sorts of things inside your templates (as you will see in a few
chapters).
❑You are limited only by what JavaScript supports as opposed to any limitations imposed by your
templating framework
❑React gives you the option to specify your visuals using an HTML-like syntax known as JSX that lives
fully alongside your JavaScript
REACT
REACT
❑Just the V in an MVC Architecture
❑React is not a full-fledged framework that has an opinion on how everything in your app should
behave
❑React works primarily in the View layer where all of its worries and concerns revolve around your
visual elements and keeping them up to date.
❑This means you are free to use whatever you want for the M and C part of your MVC Architecture
❑Consistency with existing web frameworks
LEARNING REACT
❑ It doesn’t matter if your web app was written using React or some other library like
Angular, Knockout, or jQuery.
❑The end result has to be some combination of HTML, CSS, and JavaScript
❑ JSX is a language that allows you to easily mix JavaScript and HTML-like tags to define
user interface (UI) elements and their functionality
❑ Solutions to interpret JSX
❑ Set up a development environment around Node and a handful of build-tools.
❑ JSX is automatically converted into JS and placed on disk
❑ Let your browser rely on a JavaScript library to automatically convert JSX to
something it understands.
FIRST PAGE
<script src="https://unpkg.com/react@15.3.2/dist/react.js"></script>
<script src="https://unpkg.com/react-dom@15.3.2/dist/react-
dom.js"></script>
❑ These two lines bring in both the core React library as well as the various things React needs to work
with the DOM
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-
core/5.8.23/browser.min.js"></script>
Adding a reference to the Babel JavaScript compiler (http://babeljs.io/)
❑Babel can interpret the following script <script type="text/babel">
ReactDOM.render(
<h1>Sherlock Holmes</h1>,
document.body
);
</script>
RENDER METHOD <script type="text/babel">
ReactDOM.render(
<h1>Sherlock Holmes</h1>,
document.body
);
</script>
❑The render method takes two arguments:
❑ The HTML-like elements (aka JSX) you wish to output
❑Since its jsx, not javascript, no ‘’ or “” are required for strings
❑ The location in the DOM that React will render the JSX into
PLACING THE COMPONENTS

❑Using JavaScript to place things directly in your body element is never a good idea.
❑A lot can go wrong—especially if you are going to be mixing React with other JS libraries and
frameworks.
❑The recommended path is to create a separate element that you will treat as a new root element.
❑This element will serve as the destination our render method will use

var destination = document.querySelector("#container");


ReactDOM.render(
<h1>Batman</h1>,
destination
);
REACT CODE GLIMPSE
<body>
Within CSS
<div id="container"></div> <style>
<script type="text/babel"> #container {
var destination = document.querySelector("#container"); padding: 50px;
background-color: #EEE;
ReactDOM.render(React.createElement(
}
"h1", #container h1 {
null, font-size: 48px;
"Batman" font-family: sans-serif;
), destination);
color: #0080A8;
}
</script>
</body>
</html>
REACT EXECUTION
❑JSX’s impact goes beyond how you define your UI elements.
❑It also alters how you build your app as a whole.
❑Because your browser can’t understand JSX in its native representation, you need to use an
intermediate step to convert that JSX into JavaScript.
❑ One approach is to build your app to generate the transpiled JavaScript output to correspond to the
JSX source.
❑Another approach (aka the one we used here) is to use the Babel library to translate the JSX into
JavaScript on the browser itself.
❑While the performance hit of doing that is not recommended for live/production apps, when
familiarizing yourself with React, you can’t beat the convenience.
JSX-A SYNTAX EXTENSION TO JS
function formatName(user) {
return user.firstName + '
❑const element = <h1>Hello, world!</h1>; ' + user.lastName;
}
❑This is neither a string nor HTML. This is JSX
❑You can put any valid JavaScript expression inside the curly const user = {
firstName: 'Harper',
braces in JSX lastName: 'Perez'
❑const name = 'MCA Third Year'; };

❑const element = <h1>Hello, {name}</h1>; const element = (


<h1>
❑Function call within jsx Hello,
{formatName(user)}!
</h1>
);

https://reactjs.org/docs/introducing-jsx.html
JSX FEATURES
❑You may use quotes to specify string literals as attributes:
const element = <a href="https://www.reactjs.org"> link
</a>;
❑You may also use curly braces to embed a JavaScript expression in an attribute:
const element = <img src={user.avatarUrl}></img>;
HANDLING INJECTION ATTACKS
❑JSX prevents injection attacks
❑It is safe to embed user input in JSX:
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;
❑It ensures that you can never inject anything that’s not explicitly written in your
application.
❑Everything is converted to a string before being rendered.
❑This helps prevent XSS (cross-site-scripting) attacks.
CONNECTING REACT TO THE BACKEND
LINKING NODE.JS AND REACT.JS

❑We will use the inspirational-quotes npm package


❑Within the Backend directory
$ npm init –y
❑This can be used to set up a new or existing npm package (package.json will be
created)
$ npm install express inspirational-quotes
❑This command installs a package and any packages that it depends on

https://docs.npmjs.com/cli/v8/commands/npm-install
WORKFLOW
AXIOS CORS

App.js app.js

*.jsx *.js
Proxy for
5000

Frontend @3000 Backend @5000

Application Folder
DEVELOPING THE BACKEND

const Quote = require('inspirational-


quotes');console.log(Quote.getQuote());
❑If we run this, we will see that we get a JavaScript object containing two keys: text and author
app.get("/", function(req, res) {
res.send(Quote.getQuote());
});
let port = process.env.PORT;
if(port == null || port == "") {
port = 5000;
}

❑ If we navigate over to our localhost, we should find a JSON with what we previously printed to console.
DEVELOPING THE FRONTEND
npx create-react-app frontend
❑Create React App is a comfortable environment for learning React, and is the best way to start
building a new single-page application in React.
❑It sets up your development environment so that you can
❑use the latest JavaScript features,
❑provides a nice developer experience, and
❑optimizes your app for production.

❑You’ll need to have Node >= 14.0.0 and npm >= 5.6 on your machine.
❑ npx is a package runner tool that comes with npm 5.2+
❑ It is a tool intended to help round out the experience of using packages from the npm registry
❑ The same way npm makes it super easy to install and manage dependencies hosted on the registry, npx makes it
easy to use CLI tools and other executables hosted on the registry
DEVELOPING THE FRONTEND my-app
├── README.md
├── node_modules
❑ Create-React-App uses Babel and webpack under the hood ├── package.json
❑ The initial project structure is generated and transitive dependencies ├── .gitignore
are installed ├── public
│ ├── favicon.ico
❑ No configuration or complicated folder structures, only the files you │ ├── index.html
need to build your app
│ └── manifest.json
❑ cd frontend └── src
├── App.css
❑ npm start ├── App.js
❑ Runs the app in development mode ├── App.test.js
├── index.css
❑ The page will automatically reload if you make changes to the code. ├── index.js
❑ You will see the build errors and lint warnings in the console. ├── logo.svg
└── serviceWorker.js
└── setupTests.js

https://reactjs.org/docs/create-a-new-react-app.html#create-react-app
CREATE REACT APP

The page will automatically reload if you make changes to the code.
You will see the build errors and lint warnings in the console
Inside the src directory the jsx files would be written
App.js should be linked
import React, {useState} from "react";
function Quotes() {
const [text, setText] = useState("");
const [author, setAuthor] = useState("");
CREATING A JSX return (
<div>
<button>
❑The code creates a button named Generate Quote
“Generate Quote” </button>
<h1>{text}</h1>
❑Within App.js in the frontend: <h3>{"-" + author}</h3>
</div>
import React from 'react';
)
import logo from './logo.svg';
}
import './App.css';
export default Quotes;
import Quotes from "./Quotes";
function App() {
return (
<div className="App"> At this point, running the app will simply give you a button
<header className="App-header"> and a “-”
<Quotes />
</header>
</div>
);
}
LINKING BACKEND AND FRONTEND
{ "name": "frontend",
Inside your package.json file
"version": "0.1.0",
This port MUST be different than 3000 "private": true,
"proxy":
Install a dependency called axios "http://localhost:5000",
"dependencies": {
npm install axios "@testing-library/jest-dom":
"^5.16.5",
"@testing-library/react":
"^13.4.0",
"@testing-library/user-
event": "^13.5.0",
"axios": "^1.1.3",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4" },
AXIOS

❑Axios just lets us make HTTP requests to our backend, and it works similarly to express
❑Axios is a promise-based HTTP Client for node.js and the browser.
❑It is isomorphic
❑it can run in the browser and nodejs with the same codebase
❑On the server-side it uses the native node.js http module, while on the client (browser) it uses
XMLHttpRequests
❑Intercept request and response
❑Transform request and response data
❑Cancel requests
❑Automatic transforms for JSON data
❑Client side support for protecting against XSRF
function Quotes() {
const [text, setText] =
USING AXIOS useState("");
const [author, setAuthor] =
useState("");

❑At this point, when the button is clicked, it function getQuote() {


triggers our function “getQuote”, which
axios.get("http://localhost:5000/", {
then uses axios to get the information we crossdomain: true }).then(response =>
wanted at route “/” {
❑ The information we want, our JavaScript setText(response.data.text);
setAuthor(response.data.author);
object, is given to us with response.data
});
}
CORS
Sometimes axios gets blocked by CORS, so we need to bypass this using the above
code.
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With,
Content-Type, Accept');
next();
});

Cross-Origin Resource Sharing-sharing resources among servers with same origin


https://socket.io/get-started/chat
https://socket.io/docs/v4/
https://www.geeksforgeeks.org/how-to-connect-node-js-to-a-mongodb-
database/#:~:text=To%20connect%20a%20Node.,use%20a%20library%20called
%20Mongoose.&text=method%20of%20Mongoose-
,mongoose.,%3A%20true%2C%20useUnifiedTopology%3A%20true%20%7D)%3B
https://www.mongodb.com/developer/products/mongodb/mongo-socket-chat-
example/
https://medium.com/zero-equals-false/how-to-connect-a-react-frontend-with-node-
js-bccb1fb7e2bb

You might also like