MERN Full Stack Application (Part 1/4 CRUD)-MongoDB,Express.js, Node.js (Backend) and React.js (Frontend)- Newsletter Subscription Example 3-Tier Application (Create Data)

npx create-react-app client
cd client
npm install react-bootstrap bootstrap axios
npm start

code .

import React from “react”;
import ReactDOM from “react-dom”;
import App from “./App”;

ReactDOM.render(<App />, document.getElementById(“root”));

function App() {
return (
<div>
<h1>NewsLetter</h1>
</div>
);
}

export default App;

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Newsletter</title>
</head>
<body>
<div id=”root”></div>
</body>
</html>

html,
body {
height: 100%;
}

body {
display: flex;
align-items: center;
justify-content: center;
background-color: #f5f5f5;
}

p {
color: red;
}
.success {
color: darkgreen;
text-align: center;
}

import “bootstrap/dist/css/bootstrap.min.css”;
import “./styles.css”;
import Container from “react-bootstrap/Container”;
import Form from “react-bootstrap/Form”;
import Button from “react-bootstrap/Button”;
import { useState, useEffect } from “react”;
import axios from “axios”;

function Home() {

// States to handle data,errors and form submission.
const [data, setData] = useState({ uname: “”, email: “” });
const [dataerr, setDataerr] = useState({});
const [isSubmit, setIsSubmit] = useState(false);

// function to handle changes in user input

function changeHandler(event) {
setData((prev) => {
const { name, value } = event.target;
return {
…prev,
[name]: value,
};
});
}

// Perform a post request to the server listening on port 5000(local host)

useEffect(() => {
console.log(dataerr);
if (Object.keys(dataerr).length === 0 && isSubmit) {
axios
.post(“
http://localhost:5000/posts", data)
.then((response) => console.log(response.data));
setData({ uname: “”, email: “” });
}
}, [dataerr]);

// function to handle data submission after validation

function submitHandler(event) {
setDataerr(validate(data));
setIsSubmit(true);
event.preventDefault();
}

// function to validate user input and return errors (if any)

function validate(values) {
console.log(values);
const errors = {};
const regex = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/i;
if (!values.uname) {
errors.uname = “Name is required!”;
}
if (!values.email) {
errors.email = “Email is required!”;
} else if (!regex.test(values.email)) {
errors.email = “Not valid !,Valid Format =
name@example.com”;
}
return errors;
}

// Form to gather user input

return (
<div>
<h1 className=”h3 mb-4 fw-normal”> Subscribe to the Newsletter </h1>
<Container>
<Form>
<Form.Group>
<Form.Control
name=”uname”
value={data.uname}
onChange={changeHandler}
type=”text”
placeholder=”Enter name”
required
/>
</Form.Group>
<p>{dataerr.uname}</p>
<Form.Group>
<Form.Control
name=”email”
value={data.email}
onChange={changeHandler}
type=”email”
placeholder=”
name@example.com
required
/>
</Form.Group>
<p>{dataerr.email}</p>
<br></br>
<Button onClick={submitHandler} variant=”primary btn-lg w-100">
Submit
</Button>
</Form>
</Container>
<br />
{Object.keys(dataerr).length === 0 && isSubmit ? (
<div className=”success”>Subscribed successfully</div>
) : (
<p></p>
)}
</div>
);
}

export default Home;

import Home from “./Home”;

and replace <h1>NewsLetter</h1> with <Home /> in app.js

npm init -y

npm express mongoose nodemon body-parser cors dotenv

import express from “express”;
import bodyParser from “body-parser”;
import cors from “cors”;
import dotenv from “dotenv”;
import postRoutes from “./routes.js”;
import mongoose from “mongoose”;

const app = express();

app.use(bodyParser.json({ limit: “30mb”, extended: true }));
app.use(bodyParser.urlencoded({ limit: “30mb”, extended: true }));
app.use(cors());

app.use(“/posts”, postRoutes);

const PORT = process.env.PORT || 5000;
dotenv.config()
mongoose
.connect(process.env.CONNECTION_URL, { useNewUrlParser: true, useUnifiedTopology: true })
.then(() =>
app.listen(PORT, () => console.log(`server running on port: ${PORT}`))
)
.catch((error) => console.log(error.message));

CONNECTION_URL= “mongodb+srv://<username>:<password>@clustername.mongodb.net/test?retryWrites=true&w=majority&useNewUrlParser=true&useUnifiedTopology=true”;

import express from “express”;
import {createPost } from “./controllers.js”;

//create new router object and post route

const router = express.Router();
router.post(“/”,createPost);
export default router;

import PostMessage from ‘./schema.js’

export const createPost = async(req, res) => {
const post= req.body;

const newPost= new PostMessage(post);
try {
await newPost.save();
res.status(201).json(newPost);
} catch (error) {
res.status(409).json({message :error.message});
}

import mongoose from “mongoose”;

const postSchema = mongoose.Schema({
uname: String,
email: String,
});

const PostMessage = mongoose.model(“PostMessage”, postSchema);
export default PostMessage;

npm start

POST http://localhost:5000/posts
Content-Type: application/json

{
“uname”:”cxgvfgb”,
“email”:”vfcxgb@mail.com
}

npm start

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store