React + Nodemailer: the email gets sent but it opens a new window and as well, how can I implement it on live website - javascript

I am using react + nodemailer to make a contact form for my portfolio website, however I'm having some issues.
First issue is that the email does get sent, but as soon as it sends it opens a new window with the message as part of the url, which is not supposed to happen.
Before submitting info for email
After submition of info
Second, I want to use it in a live website instead in only my localhost:3000 -> https://example.com, but I havent found anything in the docs of nodemailer.
Here is the code of the server and the react code:
import React from 'react';
import { useState } from 'react';
import './contactForm.css';
import { Footer } from '../../containers';
import axios from 'axios';
const ContactForm = () => {
//const [status, setStatus] = useState("Submit");
const [recipient_email, setEmail] = useState("");
const [name, setName] = useState("");
const [message, setMessage] = useState("");
function sendMail(){
if(recipient_email && name && message){
axios
.post('http://localhost:5000/send_email', {
recipient_email,
name,
message,
})
.then(() => alert('Message sent succesfuly'))
.catch(() => alert('Oops something went wrong'));
return;
}
return alert('Fill in all the fields to continue');
};
return (
<div className='RO__ContactForm' id='contactForm'>
<div className='RO__ContactForm-title'>
<h3>Contact</h3>
<h1>I'm here to help you level up</h1>
</div>
<div className='RO__ContactForm-content'>
<div className='RO__ContactForm-content_description'>
<p>I'm just on click away to help you take your company
to the next level. Fill in the form to share more
details about the project or your favorite movie.
Either way, I'd love to talk.</p>
<p></p>
</div>
<form
className='RO__ContactForm-content_form'
target='_blank'
>
<div className='RO__ContactForm-content_form_name'>
<div className='RO__ContactForm-content_form_nameTitle'>
<h5>What's your name?</h5>
</div>
<input
className='RO_ContactForm-content_form_nameInput'
type= 'text'
id='name'
onChange={ (e) => setName(e.target.value) }
name='name' required
/>
</div>
<div className='RO__ContactForm-content_form_email'>
<div className='RO__ContactForm-content_form_emailTitle'>
<h5>Your email</h5>
</div>
<input
className='RO__ContactForm-content_form_emailInput'
type='email'
id='email'
onChange={ (e) => setEmail(e.target.value) }
name='email' required
/>
</div>
<div className='RO__ContactForm-content_form_info'>
<div className='RO__ContactForm-content_form_infoTitle'>
<h5>What can I help you with?</h5>
</div>
<textarea
className='RO__ContactForm-content_form_infoContent'
id='message'
onChange={ (e) => setMessage(e.target.value) }
name='message' required
/>
</div>
<div className='RO__ContactForm-content_form_button'>
<button
onClick = {() => sendMail()}
type='submit'
>
Submit
</button>
</div>
</form>
</div>
<div className='RO__ContactForm-footer'>
<Footer />
</div>
</div>
)
}
export default ContactForm
server code:
const { response } = require('express');
const express = require('express');
const nodemailer = require('nodemailer');
const cors = require('cors');
const app = express();
const port = 5000;
app.use(cors());
app.use(express.json({ limit: '25mb' }));
app.use(express.urlencoded({ limit: '25mb' }));
app.use((req, res, next) => {
res.setHeader('Access-Control-Allow-Origin', '*');
next();
});
function sendEmail({ recipient_email, name, message }){
return new Promise((resolve, reject) => {
var transporter = nodemailer.createTransport({
service: 'Hotmail',
auth: {
user: '***********#hotmail.com',
pass: '**********',
},
});
const mail_configs = {
from: 'darkknight-3096#hotmail.com',
to: 'irvin.rafael.3096#gmail.com',
subject: 'Test',
text: `Name: ${name} \n Email: ${recipient_email} \n Message: ${message}`,
};
transporter.sendMail(mail_configs, function(error, info){
if(error){
console.log(error);
return reject({ message: 'An error has occured' });
}
return resolve({ message: 'Email has been sent succesfuly' });
});
});
}
app.get('/contactForm', (req, res) => {
sendEmail()
.then((response) => res.send(response.message), console.log(response.message))
.catch((error) => res.status(500).send(error.message));
});
app.post("/send_email", (req, res) => {
sendEmail(req.body)
.then((response) => res.send(response.message))
.catch((error) => res.status(500).send(error.message));
});
app.listen(port, () => {
console.log(`nodemailerProject is listening at localhost:${port}`);
});

Related

Why is message double sending to the other user in my react app?

I'm building a react app with socket-io and I'm currently experiencing a problem where when there is two users in the same room, the message from the sender will double send to the receiver. I've parsed through the code for a bit and can't figure out what is causing it. Here is the code.
Chat.js
import React, { useEffect, useState } from 'react'
function Chat({socket, username, room}) {
const [currentMessage, setCurrentMessage] = useState("");
const [messageList, setMessageList] = useState([]);
const sendMessage = async () => {
if (currentMessage != ""){
const messageData = {
room: room,
author: username,
message: currentMessage,
time: new Date(Date.now()).getHours() +
":" + new Date(Date.now()).getMinutes(),
};
await socket.emit("send_message", messageData);
setMessageList((list) => [...list, messageData]);
}
};
useEffect(() => {
socket.on("recieve_message", (data) => {
setMessageList((list) => [...list, data]);
})
},[socket]);
return (
<div className='chat-window'>
<div className='chat-header'>
<p>Live Chat</p>
</div>
<div className='chat-body'>
{messageList.map((messageContent) => {
return <h1>{messageContent.message}</h1>;
})}
</div>
<div className='chat-footer'>
<input
type="text"
placeholder="Hey..."
onChange={(event) => {
setCurrentMessage(event.target.value);
}}
/>
<button onClick={sendMessage}>►</button>
</div>
</div>
)
}
export default Chat
App.js
import './App.css';
import io from 'socket.io-client'
import {useState} from "react";
import Chat from './Chat'
const socket = io.connect("http://localhost:3001");
function App() {
const [username, setUsername] = useState("");
const [room, setRoom] = useState("");
const [showChat, setShowChat] = useState(false);
const joinRoom = () => {
if (username != "" && room != ""){
socket.emit("join_room", room)
setShowChat(true);
}
};
return (
<div className="App">
{!showChat ? (
<div className='joinChatContainer'>
<h3>Join a chat</h3>
<input type='text'
placeholder='Name?'
onChange={(event) => {setUsername(event.target.value);
}}/>
<input type='text'
placeholder='Room ID'
onChange={(event) => {setRoom(event.target.value);
}}/>
<button onClick={joinRoom}>Join A Room</button>
</div>
)
: (
<Chat socket={socket} username={username} room={room}/>
)}
</div>
);
}
export default App;
index.js
const express = require('express');
const app = express();
const http = require("http");
const cors = require("cors");
const { Server } = require("socket.io")
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors:{
origin: "http://localhost:3000",
methods: ["GET", "POST"]
}
});
io.on("connection", (socket) => {
console.log('User Connected: ' + socket.id);
socket.on("join_room", (data) => {
socket.join(data);
console.log("User with ID: " + socket.id + " joined room " + data)
})
socket.on("send_message", (data) => {
console.log(data);
socket.to(data.room).emit("recieve_message", data);
});
socket.on("disconnect", () => {
console.log("User Disconnected", socket.id);
})
})
server.listen(3001, () => {
console.log("SERVER RUNNING");
});
I'm assuming there is something that calls twice when the receiver gets the message but I can't seem to find it

Data from my react front end not getting to mysql database

I have a react front-end, node server, and MySQL database. I'm making use of express server and Axios for my post request. The code doesn't appear to have an error, also in the console and network in chrome. However, no data gets to my database. I'll really appreciate the help. Here are my codes;
Client
import React, { useState } from 'react';
import './register.css';
import {Link} from 'react-router-dom';
import Image from '../../assets/Image.png';
import Axios from 'axios';
const Register = () => {
const [uploadReq, setUploadReq] = useState('')
const [usernameReq, setUsernameReq] = useState('')
const [fullnameReq, setFullnameReq] = useState('')
const [emailReq, setEmailReq] = useState('')
const [passwordReq, setPasswordReq] = useState('')
const registration = () => {
Axios.post("http://localhost3000/register",{
upload: uploadReq,
username: usernameReq,
fullname: fullnameReq,
email: emailReq,
password: passwordReq,
}).then((response) => {
console.log(response);
});
};
return (
<div className='register section__padding'>
<div className="register-container">
<h1>register</h1>
<p className='upload-file'>Upload Profile pic</p>
<div className="upload-img-show">
<img src={Image} alt="banner" />
<p>browse media on your device</p>
</div>
<form className='register-writeForm' autoComplete='off' >
<div className="register-formGroup">
<label>Upload</label>
<input type="file" className='custom-file-input'
onChange={(e) => {
setUploadReq(e.target.value);
}}
/>
</div>
<div className="register-formGroup">
<label>Full Name</label>
<input type="text" placeholder='Name'
onChange={(e) => {
setFullnameReq(e.target.value);
}}
/>
</div>
<div className="register-formGroup">
<label>Username</label>
<input type="text" onChange={(e) => {
setUsernameReq(e.target.value);
}}placeholder='Username' />
</div>
<div className="register-formGroup">
<label>Email</label>
<input type="email" placeholder='Email'
onChange={(e) => {
setEmailReq(e.target.value);
}}
/>
</div>
<div className="register-formGroup">
<label>Password</label>
<input type="text" onChange={(e) => {
setPasswordReq(e.target.value);
}} placeholder='Password' />
</div>
<div className="register-button">
<button className='register-writeButton' onClick={registration}>register</button>
<Link to="/login">
<button className='reg-login-writeButton' >Login</button>
</Link>
</div>
</form>
</div>
</div>
)
};
export default Register;
Server
const express = require("express");
const app = express();
const mysql = require("mysql");
const cors = require("cors");
app.use(express.json());
app.use(cors());
const db = mysql.createPool({
host: "localhost",
user: "root",
password: "xyz",
database: "nftdatabase",
});
app.post('/register', (req, res) => {
const upload = req.body.upload
const Fullname = req.body.fullname
const Username = req.body.username
const Email = req.body.email
const Password = req.body.password
db.query("INSERT INTO user (upload, fullname, username, email, password) VALUES (?,?,?,?,?)",
[upload, Fullname, Username, Email, Password],
(err, result) => {
console.log(err);
});
});
app.listen(3001, () => {
console.log("running on port 3001");
});
Your server is running on PORT 3001 whereas from your client you are calling the API endpoint on PORT 3000. Have you used proxy in client side. Have you added this line in package.json file?
"proxy": "http://localhost:3001"

Having trouble in showing alert box for wrong credentials in react?

I want to show an alert box if username and password is not matching. I am sending a post request from react(using axios)to nodeJS to check for email and password. Everything is working fine if credentials are correct but it is not doing anything if it is wrong(that's understandable) but I want to show an alert when it is not correct. Why is my code not working and what would be the correct way to do it?
This is react code below:
import React, {useState} from 'react';
import "./LogIn.css";
import MailIcon from '#material-ui/icons/Mail';
import LockIcon from '#material-ui/icons/Lock';
import axios from "../axios.js";
import {useNavigate} from "react-router-dom";
function SignUp() {
// States for registration
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState(false);
let navigate = useNavigate();
// Handling the email change
const handleEmail = (e) => {
setEmail(e.target.value);
};
// Handling the password change
const handlePassword = (e) => {
setPassword(e.target.value);
};
// Handling the form submission
const handleSubmit = (e) => {
e.preventDefault();
console.log(e);
if (email === '' || password === '') {
setError(true);
} else {
setError(false);
axios.post('./login',{
email,password
}).then(function (res) {
console.log(res);
if(res.request.status === 200){
navigate(`/profile/${res.data.name}`);
}else{
alert("Username/Password is incorrect.")
};
});
}
};
// // Showing error message if error is true
const errorMessage = () => {
return (
<div
className="error"
style={{
display: error ? '' : 'none',
}}>
<h4>Please enter all the fields.</h4>
</div>
);
};
return (
<div className="form">
<form>
<h1>Log In</h1>
<p>It's quick and easy.</p>
{/* Labels and inputs for form data */}
<div className="input_field">
<MailIcon className="icon" fontSize="small"/>
<input onChange={handleEmail} className="input" placeholder="Email"
value={email} type="email" />
</div>
<div className="input_field">
<LockIcon className="icon" fontSize="small"/>
<input onChange={handlePassword} className="last-input" placeholder="Password"
value={password} type="password" />
</div>
{/* Calling to the methods */}
<div className="messages">
{errorMessage()}
</div>
<br/> <br/>
<button onClick={handleSubmit} className="btn" type="submit">
Log In
</button>
</form>
</div>
);
}
export default SignUp
This is nodeJs code:
import express from "express";
import mongoose from "mongoose";
import bodyParser from "body-parser";
import Cors from "cors";
const app=express();
const port= process.env.PORT || 5000;
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.json());
app.use(Cors());
mongoose.connect('mongodb+srv://admin:admin15#cluster0.gmg3q.mongodb.net/NotScrapDB?retryWrites=true&w=majority', {useNewUrlParser: true, useUnifiedTopology: true});
const userSchema=mongoose.Schema({
name: String,
email: String,
password: String,
});
const User= mongoose.model("User", userSchema);
app.get("/", (req,res)=>{
res.send("Hello World!Welcome to NOTSCRAP backend");
});
app.get("/register", (req, res)=>{
res.send("registered");
});
app.post("/register", (req,res)=>{
const newUser = req.body;
User.create(newUser, (err, data) => {
if(err){
res.send(err)
} else{
res.send(data);
}
});
});
app.post("/login", (req, res)=>{
const user_email = req.body.email;
const user_password = req.body.password;
if(User.findOne({email: user_email}, function(err, foundUser){
if(err){
res.send(err);
} else{
if(foundUser){
if(foundUser.password === user_password){
res.send(foundUser);
}
}
}
}))
console.log(req.body);
});
app.listen(port, ()=>{
console.log(`Server is up and running on port ${port}`);
})
Issue is in handleSubmit of the react code.
you should probably keep a variable:
const [credentialError, setCredentialError] = useState('');
....
And rather than calling alert from the error setting the value for this credentialError variable.
...
console.log(res);
if(res.request.status === 200){
setCredentialError('')
navigate(`/profile/${res.data.name}`);
}else{
setCredentialError('Credential Error (Your custom message)')
};
...
Then use this variable to show a message in the interface.

Cast to ObjectId failed for value "undefined" at path "_id" for model "User"

I've been stuck on this error for a while now, I've not been able to get it resolved searching Stack and Google. I have a ProfileScreen.js to display a user's profile. But when you click to view the profile I get this error: Cast to ObjectId failed for value "undefined" at path "_id" for model "User". From the searching I've done, I've tried rolling my version of Mongoose back, but that didn't help. Anyone have any ideas?
userRouter.js
import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import bcrypt from 'bcryptjs';
import data from '../data.js';
import User from '../models/userModel.js';
import { generateToken } from '../utils.js';
const userRouter = express.Router();
userRouter.get('/seed', expressAsyncHandler(async (req, res) => {
// await User.remove({});
const createdUsers = await User.insertMany(data.users);
res.send({ createdUsers });
}));
userRouter.post('/signin', expressAsyncHandler(async (req, res) => {
const user = await User.findOne({ email: req.body.email });
if(user) {
if(bcrypt.compareSync(req.body.password, user.password)) {
res.send({
id: user._id,
name: user.name,
email: user.email,
isAdmin: user.isAdmin,
token: generateToken(user),
});
return;
}
}
res.status(401).send({ message: 'Invalid email or password' });
}));
userRouter.post('/register', expressAsyncHandler(async(req, res) => {
const user = new User({name: req.body.name, email: req.body.email,
password: bcrypt.hashSync(req.body.password, 8),
});
const createdUser = await user.save();
res.send({
id: createdUser._id,
name: createdUser.name,
email: createdUser.email,
isAdmin: createdUser.isAdmin,
token: generateToken(createdUser),
})
})
);
userRouter.get(
'/:id',
expressAsyncHandler(async (req, res) => {
const user = await User.findById(req.params.id);
if (user) {
res.send(user);
} else {
res.status(404).send({ message: 'User Not Found' });
}
})
);
export default userRouter;
ProfileScreen.js
import React, { useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { detailsUser } from '../actions/userActions';
import LoadingBox from '../components/LoadingBox';
import MessageBox from '../components/MessageBox';
export default function ProfileScreen() {
const userSignin = useSelector((state) => state.userSignin);
const { userInfo } = userSignin;
const userDetails = useSelector((state) => state.userDetails);
const { loading, error, user } = userDetails;
const dispatch = useDispatch();
useEffect(() => {
dispatch(detailsUser(userInfo._id));
}, [dispatch, userInfo._id]);
const submitHandler = (e) => {
e.preventDefault();
// dispatch update profile
};
return (
<div>
<form className="form" onSubmit={submitHandler}>
<div>
<h1>User Profile</h1>
</div>
{loading ? (
<LoadingBox></LoadingBox>
) : error ? (
<MessageBox variant="danger">{error}</MessageBox>
) : (
<>
<div>
<label htmlFor="name">Name</label>
<input
id="name"
type="text"
placeholder="Enter name"
value={user.name}>
</input>
</div>
<div>
<label htmlFor="email">Email</label>
<input
id="email"
type="email"
placeholder="Enter email"
value={user.email}
>
</input>
</div>
<div>
<label htmlFor="password">Password</label>
<input
id="password"
type="password"
placeholder="Enter password">
</input>
</div>
<div>
<label htmlFor="confirmPassword">Confirm Password</label>
<input
id="confirmPassword"
type="password"
placeholder="Confirm password"
>
</input>
</div>
<div>
<label/>
<button className="primary" type="submit">Update Profile</button>
</div>
</>
)}
</form>
</div>
)
}
I screwed up and posted the wrong code, I posted the user router code instead of the ProfileScreen code. I've added the ProfileScreen code.
Thanks in advance for ANY help.
-N8
The issue seems to be right here:
dispatch(detailsUser(userInfo._id));
Which should, according to your user object, look like:
dispatch(detailsUser(userInfo.id));
Since _id is undefined as it does not exist in the object, you end up posting to /undefined instead of /60408c4b912e51879c7c08c4. Hence the error.
this error comes when mongoose is not able to cast the req.params.id on this line:
const user = await User.findById(req.params.id); to an ObjectId
undefined is not castable, and anyway you won't find any doc with undefined as an _id either.
You might want to check if req.params.id is undefined, and then return something based on that.
See here to see what a castable objectId is!

Sending formData with ReactJS to Express API and taking a responding JSON

Trying to get the ReactJS frontend to send in a username and password from a form to my express api via a proxy, and then have the app.post in the API return a JSON file of a user id. Proxy connection works fine, but when I send the username and password states to the API, it comes through as 'undefined' on the other end. Not sure if it's an issue with my handlers, event code/forms, or my express API.
ReactJS:
import React, { Component } from 'react'
import '../public/styles/App.css'
import Header from "./header.js"
var recID = []
export default class Login extends Component {
constructor() {
super()
this.state = {
isLoggedIn: false,
username: "",
password: "",
user: []
}
this.checkLogin = this.checkLogin.bind(this)
this.handleUsernameChange = this.handleUsernameChange.bind(this)
this.handlePasswordChange = this.handlePasswordChange.bind(this)
}
handleUsernameChange = (e) => {
this.setState({username: e.target.value});
}
handlePasswordChange = (e) => {
this.setState({password: e.target.value});
}
checkLogin(e) {
e.preventDefault()
fetch('/api/login', {
method: 'POST',
body: JSON.stringify({"user": this.state.username, "pass": this.state.password}),
headers: {'Content-Type': 'application/json'}
})
.then(response => response.json())
.then(user_id => this.setState({user: user_id}))
recID = recID.concat(this.state.user)
if (recID.length == 6) {
this.setState({isLoggedIn: true})
}
}
loginScreen() {
return(
<div style={{border:"none"}}>
<div style={{background:"white"}}>
<br></br>
<center><Header /></center>
<br></br>
</div>
<br></br>
<br></br>
<div style={{background:"white"}}>
<center><form onSubmit={e => this.checkLogin(e)}>
<br></br>
Username: <br></br>
<input type = "text" name= "username" onChange={this.handleUsernameChange}></input>
<br></br>
<br></br>
Password: <br></br>
<input type = "text" name = "password" onChange={this.handlePasswordChange}></input>
<br></br>
<br></br>
<input type = "submit" value = "Log-in"></input>
<br></br>
</form></center>
<br></br>
</div>
</div>
)
}
success() {
return (
<div>
<p>TEST</p>
{this.state.user && this.state.user.map(us => <div key={us.user_id}> {us.user_id} </div>)}
</div>
)
}
render() {
if (this.state.isLoggedIn == true) {
return (
this.success()
)
}
else {
return (
this.loginScreen()
)
}
}
}
Relevant NodeJS API Code:
'use strict'
const express = require('express')
const bodyParser = require('body-parser')
const users = require('./modules/user_management.js')
const app = express()
const port = 8080
app.use(bodyParser.urlencoded({extended: false}))
app.post("/api/login", async(req, res) => {
const id = await users.login(req.body.user, req.body.pass)
console.log(id)
res.json(id)
})
app.listen(port, () => console.log(`Server is listening on port ${port}`))
In your Node.js file, make sure to add:
app.use(bodyParser.json());
as it is currently only set up to parse urlencoded input.
Also, if that doesn't work, try removing the JSON.stringify in the fetch function, as I am not sure if that is necessary since you are already using body-parser.
EDIT - Nevermind, I was wrong about this. The JSON.stringify should be left in the original fetch call.
If neither of those two work, let me know and I'd be happy to come up with some additional suggestions.
Cheers,
Gabe

Categories