Connect nodemailer to form - node.js

I have a mail.js file that when run independently sends me a mail. And I have a form. I want to send mail to the email id that fils the form. How can I do that? I am not able to connect these two.
Where and how do I add mail.send();? And how to add variable email if both of these codes are in different files?
Also my html is in index.html
Thank you!!
index.html
<form action="/sign_up" method="POST" id="myForm">
<div>
<p class="cuboid-text">Subscribe</p>
</div>
<div>
<label for="submit" class="submit-icon">
<i class="fa fa-chevron-right"></i>
</label>
<input type="text" id="email" class="cuboid-text" placeholder="Your Email" autocomplete="off" name="email"/>
<input type="submit" id="submit" name="submit" class="submit" formaction="/sign_up" formmethod="POST"/>
</div>
<div>
<p class="cuboid-text loader">Just a moment ...
<i class="fa fa-spinner fa-pulse"></i>
</p>
</div>
<div>
<span class="reset-icon"><i class="fa fa-refresh"></i></span>
<p class="cuboid-text">Thankyou, we'll be in touch</p>
</div>
</form>
<script>
$("#email").focus(function () {
$("#cuboid form").addClass("ready");
})
//remove '.ready' when user blus away but only if there is no content
$("#email").blur(function () {
if ($(this).val() == "")
$("#cuboid form").removeClass("ready");
})
//If the user is typing something make the arrow green/.active
$("#email").keyup(function () {
//this adds .active class only if the input has some text
$(".submit-icon").toggleClass("active", $(this).val().length > 0);
})
$("#cuboid #myForm").submit(function () {
const re = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")#(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9]))\.){3}(?:(2(5[0-5]|[0-4][0-9])|1[0-9][0-9]|[1-9]?[0-9])|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/;
const email=document.getElementById("email").value;
const re1='abcd';
console.log(email);
//prevent default form submisson
if(re.test(String(email).toLowerCase())){
console.log("true");
document.getElementById("demo1").style.visibility="hidden";
$(this).removeClass("ready").addClass("loading");
setTimeout(complete, 3000);
return true;}
else{
document.getElementById("demo1").style.visibility="visible";
// setTimeout(complete, 1000);
return false;
}
})
function complete() {
$("#cuboid form").removeClass("loading").addClass("complete");
}
//reset/refresh functionality
$(".reset-icon").click(function () {
$("#cuboid form").removeClass("complete");
})
</script>
index.js
var express = require("express")
var bodyParser = require("body-parser")
var mongoose = require("mongoose")
const app = express()
app.use(bodyParser.json())
app.use(express.static('public'))
app.use(bodyParser.urlencoded({
extended: true
}))
mongoose.connect('mongodb://localhost:27017/mydb123', {
useNewUrlParser: true,
useUnifiedTopology: true
});
var db = mongoose.connection;
db.on('error', () => console.log("Error in Connecting to Database"));
db.once('open', () => console.log("Connected to Database"));
app.post("/sign_up", (req, res) => {
// var name = req.body.name;
var email = req.body.email;
// var phno = req.body.phno;
// var password = req.body.password;
// var initrefnum = req.body.demo;
// var newrefnum = req.body.newdemo;
console.log("step1");
var data = {
// "name": name,
"email": email
// "initrefnum": initrefnum,
// "newrefnum": newrefnum
}
db.collection('users').insertOne(data, (err, collection) => {
if (err) {
throw err;
}
console.log("Record Inserted Successfully");
});
// return res.redirect('index.html')
})
app.get("/", (req, res) => {
res.set({
"Allow-access-Allow-Origin": '*'
})
return res.redirect('index1.html');
}).listen(3000);
console.log("Listening on PORT 3000");
mail.js
const nodemailer=require('nodemailer')
let mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: 'mail#gmail.com',
pass: '*********'
}
});
let mailDetails = {
from: 'xyz#gmail.com',
to: 'abc#gmail.com',
subject: 'Test mail',
text: 'Node.js testing mail for GeeksforGeeks'
};
mailTransporter.sendMail(mailDetails, function(err, data) {
if(err) {
console.log('Error Occurs');
} else {
console.log('Email sent successfully');
}
});

Just this <input type="submit" id="submit" />
or
<button type="submit">Submit</button> is fine
app.use(express.static('public')) // this is enough in case if you think what more to do to wire up.
Mail.js
const nodemailer = require('nodemailer');
let mailTransporter = nodemailer.createTransport({
service: 'gmail',
host: 'smtp.gmail.com',
auth: {
user: 'dee#gmail.com', //this should be same as 'from' address
pass: 'workingpassword'
}
});
module.exports = mailTransporter;
App.js
const mailTransporter = require('./mail);
for your form action, in your /sign_up post method do below
app.post('/sign_up', (req, res)=>{
mailTransporter.sendMail({
from: 'dee#gmail.com', //this should be same as above auth.user
to: `${req.body.email}`,
subject: 'Test',
text: 'hello',
html: `Hello ${req.body.name} thank you for contacting. We will get in touch`
}).then(res=>{
console.log("success........", res)
resp.send(`email sent to ${req.body.name}` successfully);
}).catch(e=>{
console.log("failed........", e)
});
});
Things to do to avoid issues,
go to https://myaccount.google.com/lesssecureapps and enable for less secure apps.
go to https://accounts.google.com/DisplayUnlockCaptcha and enable.

Related

How do I send data from React to Node server using login form?

i'm new in react js, node js and express. I made a simple login form with username and password input form. In SignIn.js, i send username and password value to index.js ( node), but i can't get the value in index.js.
Here is the code :
SignIn.js
import Axios from 'axios';
import {
DribbbleOutlined,
TwitterOutlined,
InstagramOutlined,
GithubOutlined,
} from "#ant-design/icons";
function onChange(checked) {
console.log(`switch to ${checked}`);
}
const { Title } = Typography;
const { Header, Footer, Content } = Layout;
export default class SignIn extends Component {
constructor(props) {
super(props)
this.onChangeUsername = this.onChangeUsername.bind(this);
this.onChangePassword = this.onChangePassword.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.state = {
name: '',
email: ''
}
}
onChangeUsername(e) {
this.setState({ username: e.target.value })
}
onChangePassword(e) {
this.setState({ password: e.target.value })
}
onSubmit(e) {
e.preventDefault()
}
render() {
const onFinish = (values) => {
const username = this.state.username;
const password = this.state.password;
Axios.post("http://localhost:3001/signin", {
username : username,
password : password,
}).then((Response)=> {
console.log(Response);
});
console.log("Success:", values);
};
const onFinishFailed = (errorInfo) => {
console.log("Failed:", errorInfo);
};
return (
<>
<Layout className="layout-default layout-signin">
<Header>
<div className="header-col header-brand">
<h5></h5>
</div>
<div className="header-col header-nav">
<h5>TITLE HERE</h5>
</div>
<div className="header-col header-btn">
</div>
</Header>
<Content className="signin">
<Row gutter={[24, 0]} justify="space-around">
<Col
xs={{ span: 24, offset: 0 }}
lg={{ span: 6, offset: 2 }}
md={{ span: 12 }}
>
<Title className="mb-15">Sign In</Title>
<Title className="font-regular text-muted" level={5}>
Enter your Username and password to sign in
</Title>
<Form
onFinish={onFinish}
onFinishFailed={onFinishFailed}
layout="vertical"
className="row-col"
>
<Form.Item
className="username"
label="Username"
name="username"
id="username"
rules={[
{
required: true,
message: "Please input your Username!",
},
]}
onChange={this.onChangeUsername}
>
<Input placeholder="Username" />
</Form.Item>
<Form.Item
className="username"
label="Password"
name="password"
id="password"
rules={[
{
required: true,
message: "Please input your password!",
},
]}
onChange={this.onChangePassword}
>
<Input placeholder="Password" />
</Form.Item>
{/*<Form.Item
name="remember"
className="aligin-center"
valuePropName="checked"
>
<Switch defaultChecked onChange={onChange} />
Remember me
</Form.Item>*/}
<Form.Item>
<Button
type="primary"
htmlType="submit"
style={{ width: "100%" }}
>
SIGN IN
</Button>
</Form.Item>
{/*<p className="font-semibold text-muted">
Don't have an account?{" "}
<Link to="/sign-up" className="text-dark font-bold">
Sign Up
</Link>
</p>*/}
</Form>
Here is the code for index.js (node)
const { Result, message } = require('antd');
const express = require('express');
const app = express();
var cors = require('cors');
const mysql = require("mysql");
const db = mysql.createPool({
host: 'localhost',
user: 'root',
password: '',
database: 'wynadvm'
});
app.use(cors());
app.get('/', function (req, res) {
res.send('hello');
});
app.post('/signin', (req,res) => {
const username = req.query.username;
const password = req.query.password;
db.query(
"SELECT * from users where username = ? and password = ?",
[username , password],
(err,result) => {
if(err) {
res.send({err:err});
}
if(result.length > 0) {
res.send('result.response');
console.log(req.query.username);
//return res.redirect('/UserHomePage');
}
else
{
res.send('{message : "Wrong Username/Password Combination"}');
console.log(req.query.username);
//return res.redirect('/dashboard');
}
}
)
});
app.listen(3001,() => {
console.log("running on port 3001");
});
my username and password const always show undefined in console log.
In Front End:
Edit your import Axios from "axios" to import axios from "axios", and rewrite like this:
axios.post("http://localhost:3001/signin", {
username : username,
password : password,
}).then((response)=> {
console.log(response);
}).catch(error => console.log(error))
In Back End, if you want get value from body request from Front end
easier, install body-parser. Example:
In terminal:
$ npm install body-parser
Add some line to your Back End code:
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
And change variable you asign from query to body like:
From:
const username = req.query.username; //<--- you can't get value from query while you post data request in body
const password = req.query.password;
To:
const username = req.body.username;
const password = req.body.password;
You can use axios for making http requests to the backend.
You can learn more about axios from here: https://www.npmjs.com/package/axios
And below is an example of how you can submit login request using axios
axios.post('/signin', {
username: 'Fred',
password: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
You are sending the data in body, but you are using query to get the username and password, that's why you are getting undefined, try using
const username = req.body.username;
const password = req.body.password;

how to send email with react.js front end?

i have created a websites and deployed it ( using react js ) in my website there is a contact form which will send the client message to my work email ( myname#comany.com) . i know i can't send email with react js because rereact only handle the front end so i'm looking for a solution using nodemailer or other solutions ! how can i do that ?
i tried the following tutorials to link react with express : [https://medium.com/#maison.moa/setting-up-an-express-backend-server-for-create-react-app-bc7620b20a61][1]
i made a quick app for testing :
folder structure :
client ( created with create-react app )
node_modules
config.js
package.json
package_lock.json
server.js
in the front end : client/src
app.js code :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Form from './Form.js';
class App extends Component {
state = {
data: null
};
componentDidMount() {
// Call our fetch function below once the component mounts
this.callBackendAPI()
.then(res => this.setState({ data: res.express }))
.catch(err => console.log(err));
}
// Fetches our GET route from the Express server. (Note the route we are fetching matches the GET route from server.js
callBackendAPI = async () => {
const response = await fetch('/express_backend');
const body = await response.json();
if (response.status !== 200) {
throw Error(body.message)
}
return body;
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<Form/>
<p className="App-intro">{this.state.data}</p>
</div>
);
}
}
export default App;
Email.js code :
import React from 'react';
import { Email, Item, A} from 'react-html-email';
export default function InlineLink({name, children}) {
return (
<Email title='link'>
<Item>
Hello {name}
<p>helooo</p>
</Item>
<Item>
{children}
</Item>
</Email>
)};
Form.js code :
import MyEmail from './Email'
import { renderEmail } from 'react-html-email'
import axios from 'axios';
import React, { Component } from 'react';
class Form extends Component {
resetForm(){
this.setState({feedback: ''});
}
constructor(props) {
super(props);
this.state = { feedback: '', name: 'Name', email: 'email#example.com' };
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
render() {
return (
<form className="test-mailing">
<h1>Let's see if it works</h1>
<div>
<textarea
id="test-mailing"
name="test-mailing"
onChange={this.handleChange}
placeholder="Post some lorem ipsum here"
required
value={this.state.feedback}
style={{width: '100%', height: '150px'}}
/>
</div>
<input type="button" value="Submit" className="btn btn--submit" onClick={this.handleSubmit} />
</form>
);
}
handleChange(event) {
this.setState({feedback: event.target.value})
};
handleSubmit(event){
const messageHtml = renderEmail(
<MyEmail name={this.state.name}> {this.state.feedback}</MyEmail>
);
axios({
method: "POST",
url:"http://localhost:3000/send",
data: {
name: this.state.name,
email: this.state.email,
messageHtml: messageHtml
}
}).then((response)=>{
if (response.data.msg === 'success'){
alert("Email sent, awesome!");
this.resetForm()
}else if(response.data.msg === 'fail'){
alert("Oops, something went wrong. Try again")
}
})
}
}
export default Form;
in the backend
server.js code :
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
// create a GET route
app.get('/express_backend', (req, res) => {
res.send({ express: 'YOUR EXPRESS BACKEND IS CONNECTED TO REACT' });
});
const nodemailer = require('nodemailer');
const creds = require('./config');
var transport = {
host: 'smtp.gmail.com', // e.g. smtp.gmail.com
auth: {
user: creds.USER,
pass: creds.PASS
}
}
var transporter = nodemailer.createTransport(transport)
transporter.verify((error, success) => {
if (error) {
console.log(error);
} else {
console.log('All works fine, congratz!');
}
});
app.use(express.json()); app.post('/send', (req, res, next) => {
const name = req.body.name
const email = req.body.email
const message = req.body.messageHtml
var mail = {
from: name,
to: 'mellitir11#gmail.com',
subject: 'Contact form request',
html: message
}
transporter.sendMail(mail, (err, data) => {
if (err) {
res.json({
msg: 'fail'
})
} else {
res.json({
msg: 'success'
})
}
})
})
config.js code :
module.exports = {
USER: 'mellitir11#gmail.com',
PASS: 'my_email_password',
}
even that it shows the error message which is "Oops, something went wrong. Try again"
[1]: https://medium.com/#maison.moa/setting-up-an-express-backend-server-for-create-react-app-bc7620b20a61
Please Refer the Below code , Which is working for me..
Paste the below Code in FrontEnd i.e React (app.js)
import React,{useState,useEffect} from "react"
import Axios from 'axios'
import './App.css';
function App() {
const [frommail,setfrommail]=useState("")
const [password,setpassword]=useState(0)
const [tomail,settomail]=useState("")
useEffect(()=>{
Axios.get("http://localhost:3001/read").then((response)=>{
console.log(response.data)
})
},[])
const sendmail=()=>{
Axios.post("http://localhost:3001/mail",{frommail:frommail,password:password,tomail:tomail}).then((response)=>{
if (response.data.msg === 'success'){
alert("Email sent, awesome!");
}else if(response.data.msg === 'fail'){
alert("Oops, something went wrong. Try again")
}
})
}
return (
<div className="App">
<label>From</label>
<input type="text" onChange={(e)=>{setfrommail(e.target.value)}}/>
<label>From Mail Password</label>
<input type="text" onChange={(e)=>{setpassword(e.target.value)}}/>
<label>To address</label>
<input type="text" onChange={(e)=>{settomail(e.target.value)}}/>
<input type="submit" onClick={sendmail}/>
</div>
);
}
export default App;
Then Here is the code For Backend i.e Node js
const express = require("express");
const app = express();
const cors=require('cors')
var nodemailer = require('nodemailer');
app.use(express.json());
app.use(cors())
app.post(("/mail"),async (req,res)=>{
const frommail=req.body.frommail
const password = req.body.password
const tomail=req.body.tomail
var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: frommail,
pass: password
}
});
var mailOptions = {
from: frommail,
to: tomail,
subject: 'Sending Email using Node.js',
text: `sending mail using Node.js was running successfully. Hope it help you. For more code and project Please Refer my github page`
// html: '<h1>Hi Smartherd</h1><p>Your Messsage</p>'
};
transporter.sendMail(mailOptions, function(error, info){
if (error) {
res.json({
msg: 'fail'
});
}
else{
res.json({
msg: 'success'
})
}
});
})
app.listen(3001, () => {
console.log("Server is Running");
});
Finally Ensure that your From mail id have a less secure app access:
check this feature is enable in your gmail account
Nodemailer might do the trick for you, in essence you will need an email account that supports smtp, node v6 or above and Nodemailer Documentation (there's a how to example) it supports ssl, Oauth authentication and DKIM. Depending on what you need specificly there are other options like mailgun and mailchimp that provide APIs or backend with PHP or Java

Login System in NodeJS & Excel

So, I am creating a basic system which runs a login system in nodejs and express using an Excel file as a base. The excel CSV file will have a list of username and passwords and I am reading it using fast-csv. But when it is authenticating with the listing, it is matching only the first record. Not the other records in the excel. Any clue why? Code is as below:
index.js file
var express = require('express');
var path = require('path');
var app = express();
var bodyParser = require('body-parser');
var csv = require('fast-csv')
var fs = require('fs')
app.listen(80, function(){
console.log("Server is running")
})
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.urlencoded({extended : true}));
app.post("/", function (req,res) {
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
res.send("Login Successful. <br> Your link is available below:" + row.link)
}else{
res.send("Login Failed")
}
})
// Log file created below
var userSchema = {
Username: req.body.username,
loginDateTime: new Date().toString(),
ipAddress: req.ip,
};
fs.appendFile('logfile.txt', JSON.stringify(userSchema) + ",", function(err, file){
if(err) throw (err);
})
});
index.html file
<html>
<head>
<title>School Login Page</title>
<link rel="stylesheet" type="text/css" href="./css/mainCSS.css">
</head>
<body>
<h2>School Login Page</h2><br>
<p>Please enter all details exactly as per details provided to you.</p>
<form action="/" method="POST">
<label for="username">Username</label>
<input type="text" id="username" name="username" value="" required><br><br>
<label for="password">Password</label>
<input type="password" id="password" name="password" required><br><br>
<input type="submit" value="submit" id="submitButton">
</form>
</body>
</html>
I also want to create an alert for a failed login but I know that you cannot create alerts server side in nodejs. How can I do this is in the front-end? Thanks
The data event is fired for each row of the CSV. What you want is to check the username and password against all present records.
To achieve this, change the following:
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
res.send("Login Successful. <br> Your link is available below:" + row.link)
}else{
res.send("Login Failed")
}
})
to:
let isValid = false, rowLink;
fs.createReadStream(path.resolve(__dirname, 'master_data.csv'))
.pipe(csv.parse({ headers: true}))
.on('error', error => console.error(error))
.on('data', row => {
if(req.body.username == row.username && req.body.password === row.password && row.loggedIn == 'FALSE'){
isValid = true;
rowLink = row.link
}
})
.on('end', () => {
if (isValid) {
res.send("Login Successful. <br> Your link is available below:" + rowLink)
} else {
res.send("Login Failed")
}
})

Using axios to delete the row from mysql db.React as front end with node.js and express.js as backend

I am trying to delete the row from mysql database using axios and React.js as front end and node.js and express.js as backend. When i click the delete button the two request as send. One which shows nothing , and other which throws this in DevTools.
"Cannot DELETE /employees"
Also it does not show any console.log statements in terminal.
Below is the code for route which has the problem in delete route
const express = require("express");
const app = express();
const cors = require("cors");
const bodyParser = require("body-parser");
const logger = require("morgan");
const port = process.env.PORT || 3301;
var mysql = require("mysql");
app.use(cors());
const SELECT_ALL_USER_QUERY = 'SELECT * FROM employees';
const DELETE_QUERY = 'Delete from employees where id =';
app.use(logger('dev'));
app.use(cors());
app.use(bodyParser.urlencoded({extended : true}));
app.use(bodyParser.json());
var con = mysql.createConnection({
host: 'localhost',
user:'root',
password:"password",
database:'People'
});
con.connect(function (err){
if(err) {
console.log("Error Conneting To DB",err)
} else {
console.log("Connection Established");
}
});
//get Requets
app.get('/employees', (req, res) => {
con.query(SELECT_ALL_USER_QUERY, (err, result) => {
if(err) {
res.send(err);
} else {
let obj ={
data : result
}
console.log(obj);
res.send(result);
}
})
});
//Post Request
app.post('/employees',(req,resp)=>{
let data = {name:req.body.name , surname:req.body.surname, id:req.body.id};
let sql_query = "INSERT INTO employees SET ?"
console.log("DAATA UPLOADED")
let query = con.query(sql_query,data,(err,resp)=>{
if(err) {
console.log(err);
}
});
});
//Delete Request
// app.delete('/employees',(req,resp)=>{
// // DEBUG:
// let data = {id:req.body.id};
// let sql_query = "Delete from employees where id = ?"
// let query = con.query(sql_query,data,(err,resp)=>{
// if(err){
// console.log(err);
// }
// else {
// console.log(resp);
// }
// })
// })
// app.delete('/employees', function(req, res){
// console.log(con.query('DELETE FROM employees WHERE id =' + req.body.id));
// //con.query('DELETE FROM employees WHERE id ='+req.body.id, function(err, results){
// // if(err) throw err;
// // });
//
// // req.flash('success', 'Project Deleted');
// // res.location('/admin');
// // res.redirect('/admin');
// });
app.delete("/employees/:id", (req, res) => {
console.log("Request",req.params.id);
let { ID } = req.params.id;
let sql = `DELETE FROM employees WHERE ID = ${req.params.id}`;
console.log("HI",sql);
// delete a row with id = req.params.id
conn.query(sql, (error, results, fields) => {
if (error) return console.error("ERROR HI",error.message);
res.status(200).send(results);
console.log("Deleted Row(s):", results.affectedRows);
});
});
app.listen(4000, () => {
console.log('server running on port 4000')
})
module.exports = app;
For ReactJs there is a function deleteName in which the call for delete using axios is written. Code is below:
import React from 'react';
import './App.css';
import axios from 'axios';
class App extends React.Component {
constructor(props){
super(props);
this.onNameChange = this.onNameChange.bind(this);
this.onSurnameChange = this.onSurnameChange.bind(this);
this.onIdChange = this.onIdChange.bind(this);
this.editName = this.editName.bind(this);
this.state = {
data:'',
name:'',
surname:'',
id:''
}
}
componentDidMount() {
axios.get('http://localhost:4000/employees').then((response,err)=> {
if(err) {
console.log('err');
}
this.setState((prevstate) =>
({
data: response.data
})
);
})
}
handleSumbit(e){
axios.post('http://localhost:4000/employees',{
name: this.state.name,
surname: this.state.surname,
id:this.state.id,
}).then((response,err)=>{
if(err) {
console.log("Error While Posting Data",err);
}
console.log("RESPONSE FROM POST",response);
})
}
onNameChange(e){
this.setState({
name:e.target.value
});
}
onSurnameChange(e) {
this.setState({
surname:e.target.value
})
}
onIdChange(e){
this.setState({
id:e.target.value
});
}
editName(e,firstname,lastname,id){
this.setState({
name:firstname,
surname:lastname,
id:id
});
}
deleteName(e,value) {
axios.delete('http://localhost:4000/delete/' + value).then((response) => {
// this only runs on success
console.log("RESPONSE FROM POST", response.data);
}, (err) => {
// this only runs on error
console.log("Error While Posting Data", err);
});
}
}
render() {
const {data} = this.state;
return (
<div className="container">
<div>
<label className="">Name</label>
<input type="text" name="" value={this.state.name} onChange={(e)=>this.onNameChange(e)}/>
</div>
<div>
<label className="">Surname</label>
<input type="text" name="" value={this.state.surname} onChange={(e)=>this.onSurnameChange(e)}/>
</div>
<div>
<label className=""> YOUR ID </label>
<input type="number" name="" value={this.state.id} onChange={(e)=>this.onIdChange(e)}/>
</div>
<div>
<button type="button" onClick={(e)=> this.handleSumbit(e)}>Sumbit</button>
</div>
<div className="main-container">
<h1>Name</h1>
{
data && data.map((data,key) => {
return(
<React.Fragment>
<div className="child">
{data.name}
<button onClick={(e)=> this.editName(e,data.name,data.surname,data.id)}>Edit</button>
<button onClick={(e)=> this.deleteName(e,data.id)}>Delete</button>
</div>
</React.Fragment>
)
})
}
</div>
</div>
)
}
}
export default App;
The error "Cannot DELETE /employees" means that a route named /employees does not exist. You need to make the call to the route /delete/:id.
On another note, I noticed you were not handling the error properly in axios. The .then function takes two callbacks, the first is executed on success, and the other on error.
In total, those two things combined, try doing it like this:
axios.delete('http://localhost:4000/delete/' + value).then((response) => {
// this only runs on success
console.log("RESPONSE FROM POST", response.data);
}, (err) => {
// this only runs on error
console.log("Error While Posting Data", err);
});

How to display data from mongodb on client side?

I have created a chat app using nodejs/express, mongodb, reactjs. When I type in the chat box and on clicking send button the data get's stored inside mongodb but how can I display it on client side. In code below I am not able to display it on client side. In server.js I am not able to emit the messages. What I am doing wrong in server.js ? The data is not reaching frontend from backend/database.
Code:
server.js:
const express = require('express');
const mongoose = require('mongoose');
const socket = require('socket.io');
const message = require('./model/message')
const app = express();
const mongoURI = require('./config/keys').mongoURI;
mongoose.connect(mongoURI, {useNewUrlParser: true})
.then()
.catch( err => console.log(err));
let db = mongoose.connection;
const port = 5000;
let server = app.listen(5000, function(){
console.log('server is running on port 5000')
});
let io = socket(server);
io.on("connection", function(socket){
console.log("Socket Connection Established with ID :"+ socket.id)
socket.on('disconnect', function(){
console.log('User Disconnected');
});
let chat = db.collection('chat');
socket.on('SEND_MESSAGE', function(data){
let message = data.message;
let date = data.date;
// Check for name and message
if(message !== '' || date !== ''){
// Insert message
chat.insert({message: message, date:date}, function(){
socket.emit('output', [data]);
});
}
});
//Code below this is not working:
chat.find().limit(100).sort({_id:1}).toArray(function(err, res){
if(err){
throw err;
}
// Emit the messages
socket.emit('RECEIVE_MESSAGE', res);
});
})
chat.js:
import React, { Component } from 'react'
import './chat.css'
import io from "socket.io-client";
export default class Chat extends Component {
constructor(props){
super(props);
this.state = {
message: '',
date: '',
messages: []
};
const socket = io('localhost:5000');
this.sendMessage = event => {
event.preventDefault();
if(this.state.message !== ''){
socket.emit('SEND_MESSAGE', {
message: this.state.message,
date: Date.now()
});
this.setState({ message: '', date: '' });
}
};
socket.emit('RECEIVE_MESSAGE', data => {
addMessage(data);
});
const addMessage = data => {
console.log(data);
this.setState({
messages: [...this.state.messages, data],
});
console.log(this.state.message);
console.log(this.state.messages);
};
}
render() {
return (
<div>
<div id="status"></div>
<div id="chat">
<div className="card">
<div id="messages" className="card-block">
{this.state.messages.map((message, index) => {
return (
<div key={index} className="msgBox"><p className="msgText">{message.message}</p></div>
)
})}
</div>
</div>
<div className="row">
<div className="column">
<input id="inputmsg" type="text" placeholder="Enter Message...."
value={this.state.message} onChange={ev => this.setState({message: ev.target.value})}/>
</div>
<div className="column2">
<button id="send" className="button" onClick={this.sendMessage}>Send</button>
</div>
</div>
</div>
</div>
)
}
}
Screenshot of mongo shell:
Mongoose documentation specifies the correct usage of .find() method . You can find it here.
To cut the chase you need to give the method an object model that you are looking for. So for example if you were looking for objects with specific date field you could use:
chat.find({ "date": <some-date> }, function(err, objects) { ... });
If you want to fetch all object from the collection you can use:
chat.find({}, function(err, objects) { ... });

Resources