I am designing a contact page in which UI is rendered using React. I have a form which is supposed to send email on submit. Here is the UI code for handling submit:
handleSubmit = (event) => {
event.preventDefault();
this.setState({
disabled: true
});
Axios.post('http://localhost:3040/api/email', this.state)
.then( res => {
if(res.data.success){
this.setState({
disabled: false,
emailSent: true
});
} else{
this.setState({
disabled: false,
emailSent: false
});
}
})
.catch(err => {
this.setState({
disabled: false,
emailSent: false
});
});
}
The api to send email is written in Node.js. Used @sendgrid//mail to trigger send. On debugging I can see that the form values are reaching the api but on send it throws 403 Forbidden error. Here is the api code:
app.post('/api/email', (req, res, next) => {
sendGrid.setApiKey('<Generated key in sendgrid>');
const msg = {
to: '[email protected]',
from: req.body.email,
subject: 'Website Contact Page',
text: req.body.message
}
sendGrid.send(msg).then(result => {
res.status(200).json({
success: true
});
})
.catch(err => {
console.log('error: ', err);
res.status(401).json({
success: false
});
});
});
The following is the error trace I am getting in the VSCode console while debugging:
stack:"Error: Forbidden
at axios.then.catch.error (c:\react\portfolio-api\node_modules\@sendgrid\client\src\classes\client.js:105:29)
at process._tickCallback (internal/process/next_tick.js:68:7)"
proto:Error {constructor: , toString: , toJSON: }
Not sure why its giving me Forbidden error. Please let me know if I need to add more info here. Thanks in advance :)
EDIT:- Followed the doc here at sendgrid to create an API key and used the same in sendGrid.setApiKey().
