how to send email with react.js front end? - node.js

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

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 the data to server in react?

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,
};

I want to tell reactjs login component whether login was successful or not

I am confused as to how to communicate from the nodejs server to the reactjs login component on whether login was successful or not.
I have a reactjs component that handles login as follows:
Login.js
import React, {useState} from 'react';
import axios from "axios";
const Login = () => {
const [user,setUser] = useState({email:"",password:""});
const handleSubmit = (e) => {
e.preventDefault();
console.log(user);
axios.post('http://localhost:5000/login',user)
.then(function (response) {
console.log(response);
console.log("Successfully done");
})
.catch(function (error) {
console.log("error here")
console.log(error.message);
});
}
return (
<div>
<h1>Login</h1>
<form onSubmit={handleSubmit}>
<div>Email:</div>
<div><input type="text" name="email" placeholder='Enter your email'
onChange={(e)=>setUser({...user,email:e.target.value})}
/></div>
<div>Password:</div>
<div><input type="password" name="password" placeholder='Enter your password'
onChange={(e)=>setUser({...user,password:e.target.value})}
/></div>
<div><input type="submit" value="Add" /></div>
</form>
</div>
)
}
export default Login;
and an expressjs backed that processes the login
server.js
const express = require("express");
const mongoose = require("mongoose");
const User = require("./Models/Conn.js");
const bcrypt = require("bcryptjs");
//const Route1 = require("./Routes/Route.js");
const cors = require('cors');
const app = express();
//app.use("/api",Route1);
app.use(express.json({extended:true}));
app.use(express.urlencoded({extended:true}));
app.use(cors());
const url = "mongodb+srv://pekele:pekele#cluster0.yqaef.mongodb.net/myDatabase?retryWrites=true&w=majority";
mongoose.connect(url)
.then(()=>console.log("connected to database successfully"))
.catch(err=>console.log(err));
app.get("/",(req,res)=> {
res.send("<h1>Welcome Guest</h1>");
});
app.get("/signup",(req,res)=> {
res.json({"id":"1"});
})
app.post("/signup",(req,res)=> {
const {email,password} = req.body;
bcrypt.genSalt(10)
.then(salt=> {
bcrypt.hash(password,salt)
.then(hash => {
const user = new User({email,password:hash});
user.save()
.then(()=>console.log("Successfully saved"))
.catch(error=>console.log(error));
})
}).catch(err=>console.log(err));
})
app.post("/login",(req,res)=> {
const {email,password} = req.body;
console.log(`My email is ${email}`)
User.findOne({email:email}, function (err, doc) {
console.log(doc);
if(doc == null) {
//How do i let react login page know that there is no user with such email
}
if(doc != null) {
const emailDB = doc.email;
const passwordDB = doc.password;
bcrypt.compare(password,passwordDB)
.then(res => {
//How do I tell the react login page that the login was successful
}).catch(err=>console.log(err));
}
});
})
app.listen(5000,()=> console.log("Server listening on port 5000"));
The problem is how do I communicate to the react login page whether the login was successful or not in the app.post("/login",(req,res) ... Thanks
You can send data via -
res.json(data)
res.send("Submitted Successfully!")
res.status(200).send(message)

Network error from using localhost when web app is launched with Netlify

I just deployed a Spotify web app with Netlify. It works fine when it's running on my computer but it doesn't work on others. It shows Network Error, POST http://localhost:4000/search_result net::ERR_CONNECTION_REFUSED. I changed the url of the axios request to "/search_result" but it still didn't work. How should I fix it?
Here's my code.
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;
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}`));
It is likely that the server code isn't running as you expect it to.
Think about what commands you run to get that localhost server running on your machine, compared to the build command you provided o Netlify to build your site.
Netlify is primarily for hosting static sites, so will not automatically provide a backend server for you to use.
You can either host the server part of your app on something like Heroku (and then have to hard-code the URL of that server instance into your app), or you can use Netlify Functions to handle your basic post request, which will let you use the relative URLs as in your question.

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