How to send email with ReactJS and SendGrid? - node.js

I have setup and account on SendGrid. I have got the API key and Node.js methods. I am creating an web app with React js. I want to send emails through SendGrid. I am unable to find any solution. Please help me with my question with an example.

Its not possible with react as it is a frontEnd library, if you try to implement with react you will get these errors
---> Refused to set unsafe header "User-Agent"
If you need to set those headers then you'll need to make the request from your server and not your visitor's browser.
So this is not possible from react and you will need to use some backend or firebase for it.

//Form.js
class Form extends React.Component {
constructor() {
super();
this.handleSubmit = this.handleSubmit.bind(this);
}
handleSubmit(event) {
event.preventDefault();
const data = new FormData(event.target);
fetch('/api/form-submit-url', {
method: 'POST',
body: data,
});
}
render() {
return (
<form onSubmit={this.handleSubmit}>
<label htmlFor="username">Enter username</label>
<input id="username" name="username" type="text" />
<label htmlFor="email">Enter your email</label>
<input id="email" name="email" type="email" />
<label htmlFor="birthdate">Enter your birth date</label>
<input id="birthdate" name="birthdate" type="text" />
<button>Send data!</button>
</form>
);
}
}
//index.js
const sgMail = require('#sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);
const msg = {
to: test#example.com',
from: 'test#example.com',
subject: 'Sending with SendGrid is Fun',
text: 'and easy to do anywhere, even with Node.js',
html: '<strong>and easy to do anywhere, even with Node.js</strong>',
};
sgMail.send(msg);

You can use MailJS, and use sendgrid for transactional services.
It's easy to use.

There are multiple solutions available.
You could use nodeMailer : https://nodemailer.com/about/
Node mailer even has transport dwritten specifically for Sendgrid : https://www.npmjs.com/package/nodemailer-sendgrid-transport
You could use node package by sendgrid itself : https://github.com/sendgrid/sendgrid-nodejs/tree/main/packages/mail

Related

Search Data not working Angular NodeJS API

i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>
What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.
To achieve the equivalent of what you do in Postman, you could use the following code:
search(firstName: string) {
const params = new HttpParams().set('first_name', firstName);
const body = {
first_name : firstName
};
this.http.post("http://localhost:9001/user/findOne", body, { params: params })
.subscribe((resultData: any)=>
{
console.log(resultData);
});
}
Btw: Why don't you use GET instead of POST?

Post image file using axios in react app sending strange data to backend

I'm currently trying to post a photo file upload to my backend, to be stored in the file system. However, whenever I do, it produces an absolutely bizarre string of numbers / letters when I console log the req.body.
I've no idea what this is, why it's happening or how to convert it into the image I need to store in my file system.
Here's my uploadPhoto and buttonClick (aka submit) functions:
const uploadPhoto = (e) => {
e.preventDefault()
setPreviewPhoto(URL.createObjectURL(e.target.files[0]))
setPhotoFile(e.target.files[0])
}
const buttonClick = async (e) => {
e.preventDefault()
const formData = new FormData()
formData.append('photoFile', photoFile)
await axios.post("/api/uploadProfilePicture", formData, { headers: { 'content-type': 'multipart/form-data' }}, { transformRequest: formData => formData })
}
And here's my form that's used to upload the image:
<form className="setup-form" method="POST" encType="multipart/form-data" onSubmit={buttonClick}>
<label className="setup-label">Your name</label>
<input className="setup-input" type="text" name="name" onChange={onChange} value={name} />
<label className="setup-label">Your photo</label>
<div className="setup-photo-hint-container">
<div className="setup-photo-div">
<label for="photoFile" className="setup-photo-label">Upload</label>
<input className="setup-photo-input" id="photoFile" type="file" onChange={uploadPhoto} name="photoFile" />
</div>
</div>
</form>
Does anyone have any idea what I'm doing wrong here? I don't understand why it's going to the request body for one, or why it's producing these characters for another.

Connecting Node.js with React

I am new to react and am working on my first project, I have a question on how to connect react with node.js.I have a post page where you can post data and I want to get that data in node.js so that I can connect it with MongoDB.
Here's my code
Post component
import React from "react";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faPlus } from "#fortawesome/free-solid-svg-icons";
import "./componentStyles/postStyles.css";
const element = <FontAwesomeIcon icon={faPlus} />;
function Post() {
return (
<div>
<h2>Post your data here</h2>
<form className="post-form">
<input className="inputTitle" name="title" placeholder="Title" />
<textarea
className="inputContent"
name="content"
placeholder="Content"
rows="3"
/>
<input
className="inputTitle"
name="contact"
placeholder="contact details"
/>
<br />
<br />
<label className="inputTitle" for="CompanyType">
Company Type:{" "}
</label>
<select>
<option value="AI">AI</option>
<option value="Stocks">Stocks</option>
<option value="Finance">Finance</option>
<option value="Medical">Medical</option>
<option value="Engineering">Engineering</option>
<option value="Construction">Construction</option>
</select>
<button className="submitBtn">{element}</button>
</form>
</div>
);
}
export default Post;
Post page
import React from "react";
import Post from "../components/Post";
const Contact = () => {
return (
<div
style={{
display: "flex",
justifyContent: "center",
alignItems: "center",
height: "90vh",
}}
>
<Post />
</div>
);
};
export default Contact;
Thanks in advance for Answers
There's not one "standard" way of doing this. There are several ways to do it, such as:
using redux and redux middlewares like redux-saga and redux-thunk
with hooks (react-query is worth looking at)
with a simple abstract API manager
directly inside the component (not recommended)
Anyway, React is JavaScript at the end of the day, so you need a client to make HTTP requests to the API. Many use axios.
A pseudo code example:
// APIManager.js
export const getPosts = () => {
return axios.get(`${baseUrl}/posts`).then(resp => resp.data);
};
// Post.jsx
const Post = () => {
const [posts, setPosts] = useState([]);
useEffect(() => {
APIManager.getPosts().then(res => setPosts(res));
}, []);
};
Also, there are many other client libraries that you can use for this purpose.
You need to set up a nodejs environment.
Add Express or Koa to handle requests.
Add Mongodb -> use mongo atlas and add the end point to the backend. Make sure to configure your Mongodb Atlas environment to handle requests.
Add the routes that you want to your backend to handle the data exchanges.
Use Fetch or Axios on the front end to get, post, put, delete data.
There are courses and articles that cover this more in detail. I suggest checking them out, because you will need to understand some of nuances that are specific for your use case, such as working with mongodb. This post could be turned into a book, but I just wanted to help guide you in the right direction.

How to handle response in react

I am new to react. Currently I am working on creating a login screen. I have this code:
function login(e) {
fetch('/login')
.then(response => {
if(response === 'fail'){
return(SignIn());
}else{
return(Ide());
}
})
.then((proposals) => {
console.log(proposals);
this.setState({ proposals });
});
}
export default function SignIn() {
const classes = useStyles();
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="email"
label="Email Address"
name="email"
autoComplete="email"
autoFocus
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
/>
<Button
type="submit"
fullWidth
onClick={login}
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
</form>
</div>
</Container>
);
And then the login handler
app.get('/login', (req, res, next) => {
const { email, password } = req.body;
console.log(email, password);
//User.find({email: })
});
But when I press the submit button, email and password both console log as undefined. How do I send information using react between the client and the server? Thank you in advance
Whenever you use fetch as a way to send info to an endpoint like '/login' above, the req.body needs to be added as part of the fetch call. To do this, people usually do
fetch('/login', {
body: (whatever you send in the form of one object)
});
The body passed in as the second argument can be then used as req.body in your code that console.logs it.
This is not advised though since GET commands usually do not have bodies passed along as the second argument. Usually POST and PUT commands have the body to make it easy to add and change data. What I recommend is do:
fetch('/login/' + email + '/' + password);
This allows for an email and username object to be a part of your url in for your backend to use. This is one of the ways that people do GET commands without passing in a body. With the new format, you should change the backend to be:
app.get('/login/:email/:password', (req, res) => {
const email = req.params.email;
const password = req.params.password;
console.log(email, password);
With :email and :password in the url, this lets you use req.params and then directly call each identifier as the last value.
Btw if you feel like the fetch call above looks messy with the + commands, you can instead do:
fetch(`/login/${email}/${password}`);
Which are Template Literals that make it easier to read code by adding the values directly into the string. (Note they use the ` key next to the 1 key not ' or ")
Also if you want more info on fetch commands, I advise to start with the MDM Documentation. This website is extremely helpful whenever you need to learn something about JS or other web languages.

Response with express and nodejs application

I have an express server and a login page developed in HTML(with jquery). after login button is hit, jQuery fires a HTTP get request to express server and after user gets verified, user should be redirected to landing page with some data like name, gender, age etc(that is fetched from mongoDB on server itself). When I do res.sendFile or res.redirect, The parameters (name, age, gender) could not be sent on the view which is required there in response.
Jquery:
$("#submit").click(function() {
user = $("#email").val();
pass = $("#password").val();
$.post("https://localhost:443/login", {
user: user,
password: pass
}, function(response) {
if (response) {
alert("login success" + response.userName);
}
});
});
HTML:
<form id="grad">
<h1 style="margin-top: -10px; text-shadow: 1px 1px whitesmoke;">Login</h1>
<h3 style="padding-bottom: 30px;font-size: 22px ">Please enter email ID and password.</h3>
<div class="group">
<input type="email" id="email" name="email"><span class="highlight"></span><span class="bar"></span>
<label>Email ID</label>
</div>
<div class="group">
<input type="password" id="password" name="password"><span class="highlight"></span><span class="bar"></span>
<label>Password</label>
</div>
<div class="group">
<input type="submit" id="submit" class="button buttonRed" value="Login" onclick="validateUser()" />
<input type="reset" class="button buttonRed" value="Reset" />
</div>
</form>
Express:
app.post('/login', function (req, res) {
// some logic to validate user and fetch details, which will be used on view.
res.sendFile('landing**strong text**page.html', { root: "public" } );
})
The post route should save the user in session before returning the response to jQuery code. Essentially the response from post route should be only success or response.
There should also be a get route to redirect the user to home page (or the page where u want the user after login).
This get route will first check if there is a user in session then redirect accordingly.
Use express-session to save the session in app.
Simple solution for starter. This is NOT a practical solution in production site, just for starter who wants to learn the basic.
Jquery
$("#submit").click(function() {
user = $("#email").val();
pass = $("#password").val();
$.post("https://localhost:443/login", {
user: user,
password: pass
}, function(response) {
$('body').append(response); //append html to body returned from /login
});
});
Express Server:
app.post('/login', function (req, res) {
// some logic to validate user and fetch details, which will be used on view.
var userInfo = validateAndFetchDetailFunc();
res.send('Username: ' + userInfo.name + '<br>Gender: ' + userInfo.gender);
})
The real solution should be using session to management the login session for user.
User login with username/password
Create a session at the server side, send back a session key or access token to the client.
When the client request user information, use the session key or access token to retrieve the user info
Render the html page with the user info from the saved session
For express server, you can start to learn session with express-session.

Resources