How to send the data to server in react? - node.js

Please help me to fix my issue.
I am building react project using material ui.
This is contact us part in my project.
I want to send email when visitor see this site then.
Backend is working well with postman. But when I use front end request, Backend don't receive any values.
This is my code(Front).
import { React, useState } from 'react';
import axios from 'axios';
// material
import { Button, Typography, TextField, Stack } from '#material-ui/core';
//
import { varFadeInUp, MotionInView } from '../../animate';
// ----------------------------------------------------------------------
export default function ContactForm() {
const [name, setName] = useState('');
const [email, setEmail] = useState('');
const [subject, setSubject] = useState('');
const [message, setMessage] = useState('');
const basicUrl = 'http://localhost:8080/';
const handleEmailSender = (e) => {
e.preventDefault();
const data = {
name,
email,
subject,
message
};
axios.post(basicUrl, data).then((res) => {
console.log(res);
});
};
const handleNameChange = (e) => {
setName(e.target.value);
};
const handleEmailChange = (e) => {
setEmail(e.target.value);
};
const handleSubjectChange = (e) => {
setSubject(e.target.value);
};
const handleMessageChange = (e) => {
setMessage(e.target.value);
};
return (
<Stack spacing={5}>
<MotionInView variants={varFadeInUp}>
<Typography variant="h3">
Feel free to contact us. <br />
We'll be glad to hear from you
</Typography>
</MotionInView>
<Stack spacing={3}>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Name" onChange={handleNameChange} />
</MotionInView>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Email" onChange={handleEmailChange} />
</MotionInView>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Subject" onChange={handleSubjectChange} />
</MotionInView>
<MotionInView variants={varFadeInUp}>
<TextField fullWidth label="Enter your message here." multiline rows={4} onChange={handleMessageChange} />
</MotionInView>
</Stack>
<MotionInView variants={varFadeInUp}>
<Button size="large" variant="contained" onClick={handleEmailSender}>
Submit Now
</Button>
</MotionInView>
</Stack>
);
}
This is my backend Code.
const express = require("express");
const cors = require("cors");
const app = express();
const nodemailer = require("nodemailer");
app.use(cors());
// This responds with "Hello World" on the homepage
app.post("/", function (req, res) {
response = {
name: req.query.name,
email: req.query.email,
subject: req.query.subject,
message: req.query.message,
};
console.log(response.name);
let mailTransporter = nodemailer.createTransport({
service: "gmail",
auth: {
user: "xxxxxx",
pass: "xxxxxx",
},
});
let mailDetails = {
from: response.email,
to: "xxxxxxx",
subject: response.subscribe,
text: response.message,
};
mailTransporter.sendMail(mailDetails, function (err, data) {
if (err) {
console.log("Error Occurs");
} else {
console.log("Email sent successfully");
}
});
res.send();
});
// This responds a GET request for the homepage
// app.get("/", function (req, res) {
// console.log("Got a GET request for the homepage");
// res.send("Hello GET");
// });
app.listen(8080, function () {
console.log("Server is running at http://localhost:8080/");
});
Please help me please :-)

Try using req.body and have a look at this post on how to append form data: axios post request to send form data
app.post("/", function (req, res) {
console.log({req})
response = {
name: req.body.name,
email: req.body.email,
subject: req.body.subject,
message: req.body.message,
};

Related

Redirects to wrong page when logging in

it redirects to an empty js file when logging in, not to the js file I wrote. Should I redirect in my database code?
////////////////
const client = require('../../db')
const express = require('express');
const app = express();
const cors = require("cors");
app.use(cors());
app.use(express.json()); //req.body
app.listen(2136, ()=>{
console.log("Sever is now listening at port 5000");
})
client.connect();
app.post("/login", async (req, res) => {
try {
const { email, password } = req.body;
const user = await client.query(
`SELECT * FROM users WHERE email=$1 AND password=$2`,
[email, password]
);
if (user.rows.length === 0) {
res.status(404).send("Kullanıcı adı veya şifre yanlış");
} else {
res.send("Kullanıcı adı veya şifre doğru");
}
}catch (err) {
response
.status(500)
.json({ message: "Error in invocation of API: /login" })
}
});
this is my database code.
///////////////////////
import {
BrowserRouter as Router,
Route
} from "react-router-dom";
import React, { useState } from 'react'
import Navbar from '../../common/Navbar/Navbar';
import AdminPage from './AdminPage';
const User = () => {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [user, setUser] = useState([]);
const [error, setError] = useState('');
const onSubmitForm = async e => {
e.preventDefault();
try {
const response = await fetch(`http://localhost:2136/login`,{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, password }),
});
console.log(email,password)
console.log(response);
if ((response.status)===404) {
setError('Invalid email or password');
} else
{
window.location.replace(`/AdminPage`);
}
} catch (err) {
console.error(error);
setError('An error occurred. Please try again later.');
}
};
return (
<>
<Navbar/>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.4.1/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"></link>
<div className="container text-center">
<h1 className="my-5">Search for the Dormitory You Want</h1>
<form className="d-flex" onSubmit={onSubmitForm}>
<input
type="text"
name="name"
placeholder="Enter email ..."
className="form-control"
value={email}
onChange={e => setEmail(e.target.value)}
/>
<input
type="text"
name="name"
placeholder="Enter password ..."
className="form-control"
value={password}
onChange={e => setPassword(e.target.value)}
/>
<button className="btn btn-success">Submit
</button>
</form>
</div>
</>
)
}
export default User
this is my login page. the page it redirects to is a blank page. i don't understand why.
///////////////
import React, { useState } from 'react'
import AdminNavbar from '../../common/Navbar/AdminNavbar';
const AdminPage = () => {
return (
<>
<AdminNavbar/>
</>
);
}
export default AdminPage
and this the page I want to redirect AdminPage.So what can i do?
///////////////////
The difference between assign() and replace():
replace() removes the current URL from the document history.
With replace() it is not possible to use "back" to navigate back to the original document.
You can use assign method instead of location method

How to connect Express JS to NotionAPI with POST and GET

I am very new to backend so I am trying to implement a simple Notion form on a Typescript website. I was following this tutorial: https://commotion.page/blog/how-to-create-a-form-app-with-the-notion-api to learn how to post from localhost:3000 to the Notion backend database which looks exactly like the one in the tutorial. However, every time I reload the page I get this error:
Here is the code for my express server, app.js (exactly the same as the one in the tutorial):
const express = require('express')
const axios = require('axios')
const cors = require('cors')
const app = express()
const port = 3002
const secretKey = 'secret_[KEY REPLACED]'
const headers = {
'Content-Type': 'application/json',
Authorization: `Bearer ${secretKey}`,
'Notion-Version': '2022-02-22',
}
app.post('/704f58825cf841759f76733c5794e8aa', async (req, res) => {
const { name, email } = req.body
await axios({
method: 'POST',
url: 'https://api.notion.com/v1/pages',
headers,
data: {
parent: { dat704f58825cf841759f76733c5794e8aaabase_id },
properties: {
"Name": { "title": [{ text: { content: name } }] },
"Email": { "email": email }
}
}
})
})
app.get('/:database_id', async (req, res) => {
const { database_id } = req.params;
const resp = await axios({
method: 'GET',
url: 'https://api.notion.com/v1/databases/' + database_id,
headers
});
return res.json(resp.data)
})
app.use(cors())
app.use(express.json())
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
I am using ChakraUI for my front-end as well. This is the code for my main app, which is located outside of the server folder in the main app folder:
const database_id = '[KEY REPLACED]';
export default function ContactFormWithSocialButtons() {
const { hasCopied, onCopy } = useClipboard('intellimindsBR#gmail.com');
const [db, setDB] = useState({});
const [email, setEmail] = useState('');
const [name, setName] = useState('');
const onSubmit = (e) => {
e.preventDefault();
console.log(name);
console.log(email);
fetch('http://localhost:3002/' + database_id, {
method: 'POST',
body: JSON.stringify({ email: email, name: name }),
headers: { "Content-Type": 'application/json' }
});
}
useEffect(() => {
fetch('http://localhost:3002/' + database_id).then(async (resp) => {
setDB(await resp.json());
});
}, []);
return (
<Box
bg={useColorModeValue('white', 'gray.700')}
borderRadius="lg"
p={8}
color={useColorModeValue('gray.700', 'whiteAlpha.900')}
shadow="base">
<VStack spacing={5}>
<form onSubmit={onSubmit}>
<FormControl isRequired>
<FormLabel>Name</FormLabel>
<InputGroup>
<InputLeftElement children={<BsPerson />} />
<Input type="text" name="name" placeholder="Your Name"
onChange={event => setName(event.currentTarget.value)} />
</InputGroup>
</FormControl>
<FormControl isRequired>
<FormLabel>Email</FormLabel>
<InputGroup>
<InputLeftElement children={<MdOutlineEmail />} />
<Input
type="email"
name="email"
placeholder="Your Email"
onChange={event => setEmail(event.currentTarget.value)}
/>
</InputGroup>
</FormControl>
<Button
type="submit"
colorScheme="blue"
bg="blue.400"
color="white"
_hover={{
bg: 'blue.500',
}}>
Send Message
</Button>
</form>
</VStack>
</Box>
);
}
When I load the server with node app.js, everything works fine and the title of the database successfully loads onto the production page but as soon as I enter data to submit in the form I get this response:
I also get this error in console for my app.js page when I submit the form:
const { name, email } = req.body
^
TypeError: Cannot destructure property 'name' of 'req.body' as it is undefined.
I will also mention that when I load the server with node app.js, the error Cannot GET / but all the data loads fine when I go to the API URL with the database ID in the URL (http://localhost:3002/[database ID]).
I have properly configured the Notion API integration and I have tried enabling Access-Control-Allow-Origin for Chrome, but I'm still facing these errors.
Before you can access req.body, you must use a body-parsing middleware like express.json:
app.post('/704f58825cf841759f76733c5794e8aa',
express.json(),
async (req, res) => {
const { name, email } = req.body
...
})

post route is not working for user registeration

This is the code for my post route. I am using registerPost to post a new user to mongoDB data base. Have a User schema made. The code for my registerPost function doesn't seem to be running.
export const registerPost = async (req, res) => {
const {username, password} = req.body;
const newUser = new User({username, password});
try {
await newUser.save();
console.log(newUser);
res.status(201).json(newUser);
} catch (error) {
res.status(409).json({ message: error.message });
}
}
These are the routes. Am not able to get a the /auth to go through on form submit. No console log no anything. I am missing something but am not sure.
import express from 'express';
import { getPosts } from '../controllers/posts.js'
import { createPost, updatePost, deletePost, registerPost } from '../controllers/posts.js'
const router = express.Router();
router.get('/', getPosts);
router.post('/', createPost);
router.patch('/:id', updatePost);
router.delete('/:id', deletePost);
router.post('/auth', registerPost);
export default router;
This is the react form code for the register part.
import React, { useEffect, useState } from 'react';
import { TextField, Button, Typography, Paper } from '#material-ui/core';
import useStyles from './styles.css';
const Auth = () => {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const divStyle = {
backgroundColor: 'white',
};
return (
<div style = {divStyle}>
<form>
<h1>Registration</h1>
<TextField
name='username'
variant='outlined'
label='username'
fullWidth
onChange={(e) => {
setUsername( e.target.value)
}}
/>
<TextField
name='password'
variant='outlined'
label='password'
fullWidth
onChange={(e) => {
setPassword( e.target.value)
}}
/>
<Button variant="container" color="primary" size="large" type="submit" fullwidth>Register</Button>
</form>
</div>
);
}
export default Auth;
Api doc
import axios from 'axios';
const url = 'http://localhost:5000/posts';
export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);
export const updatePost = (id, updatedPost) => axios.patch(`${url}/${id}`, updatedPost);
export const deletePost = (id) => axios.delete(`${url}/${id}`);
export const likePost = (id) => axios.patch(`${url}/${id}/likePost`);

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

Why is my website running fine on my computer but not on other's?

I made a Spotify web app and launched it with Netlify. When I run its server file, it works well on my computer but not on my friend's. I thought it was because of the Spotify API at first but another web app I made, which doesn't use any API, only works on my computer as well. I think it's because of the server port or something but I'm not sure how to fix it.
Here's the website url and the server side code.
https://xenodochial-kepler-118793.netlify.app
server.js
const express = require("express");
const SpotifyWebApi = require("spotify-web-api-node");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 4000 || process.env.PORT;
require("dotenv").config();
app.use(express.json());
app.use(cors());
app.use(bodyParser.urlencoded({ extended: true }));
// Create the api object with the credentials
var spotifyApi = new SpotifyWebApi({
clientId: process.env.CLIENT_ID,
clientSecret: process.env.CLIENT_SECRET,
});
// Retrieve an access token.
function newToken() {
spotifyApi.clientCredentialsGrant().then(
function (data) {
console.log("The access token expires in " + data.body["expires_in"]);
// Save the access token so that it's used in future calls
spotifyApi.setAccessToken(data.body["access_token"]);
},
function (err) {
console.log("Something went wrong when retrieving an access token", err);
}
);
}
newToken();
tokenRefreshInterval = setInterval(newToken, 1000 * 60 * 60);
app.post("/search_result", (req, res) => {
spotifyApi
.searchArtists(req.body.keyword)
.then(function (data) {
let search_res = data.body.artists.items;
res.json(search_res);
res.end();
})
.catch((err) => {
console.log(err);
res.status(500).send(err);
});
});
app.get("/albums/:id", (req, res) => {
console.log(req.params.id);
spotifyApi
.getArtistAlbums(req.params.id, { limit: 40 })
.then(function (data) {
res.json(data.body.items);
res.end();
});
});
app.get("/albums/tracks/:albumID", (req, res) => {
console.log(req.params.albumID);
spotifyApi
.getAlbumTracks(req.params.albumID, { limit: 20 })
.then(function (data) {
console.log(data.body);
res.json(data.body.items);
res.end();
});
});
app.listen(port, () => console.log(`It's running on port ${port}`));
Main.js
import React, { Component } from "react";
import SingerBox from "./SingerBox";
import axios from "axios";
import "../../App.css";
export class Main extends Component {
constructor(props) {
super(props);
this.state = {
keyword: "",
artists: [],
};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({ keyword: e.target.value });
}
handleSubmit(e) {
e.preventDefault();
if (this.state.keyword === "") {
alert("Enter Search Keyword");
}
axios
.post(
"/search_result",
{
keyword: this.state.keyword,
},
{
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
}
)
.then((res) => {
this.setState({ artists: res.data });
})
.catch((err) => {
console.log(err);
});
}
render() {
return (
<div className="container">
<div className="main">
<form onSubmit={this.handleSubmit}>
<label className="header" htmlFor="search">
Explore New Artists
</label>
<span>
<input
className="search-box"
type="search"
value={this.state.keyword}
onChange={this.handleChange}
name="keyword"
placeholder="Search artists..."
/>
<button className="submit-btn" type="submit" value="Submit">
Search
</button>
</span>
</form>
<br />
{this.state.artists.map((elem) => (
<SingerBox images={elem.images} name={elem.name} id={elem.id} />
))}
<br />
</div>
</div>
);
}
}
export default Main;
You have hardcoded localhost in your code somewhere. The apis are hitting your local server when someone is searching for the artist.
Remove localhost from code and every thing should work fine.

Resources