Trouble setting up form with Sendgrid API in express app

Trouble setting up form with Sendgrid API in express app
0.0 0

#1

I want to implement Sendgrid’s API to receive e-mail to a certain gmail account whenever someone submits the contact me form. The project I am on is made with react (for routing using react-router if that’s relevant) and express.

Then only thing that happens after submitting is “cannot POST /contanct”.

Feel lost with this, so some guidance on what I ma doing wrong will be really appreciated!

Here is the form :

export default () => (
  <div className="contact">
      <div className="contact__form">
          <form method="post" action="/contact">
            <input name="firstName" field="firstName" placeholder='Name' />
            <input name="e-mail" field="e-mail" placeholder='E-mail' />
            <input name="subject" field="subject" placeholder='Subject' />
            <input name="message" field="message" placeholder='Message' />
            <button type="submit">Submit</button>
          </form>
      </div>
  </div>
);

And here is the server.js file :

const path = require('path');
const express = require('express');
const publicPath = path.join(__dirname, '../public');
const port = process.env.PORT || 3000;
const sgMail = require('@sendgrid/mail');
sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const app = express();

app.use(express.static(publicPath));

app.post('/contact', (req, res) => {
  const msg = {
    to: 'name.surname@gmail.com',
    from: 'name@inbox.lv',
    subject: 'Hello world',
    text: 'Hello plain world!',
    html: '<p>Hello HTML world!</p>',
  };
  sgMail
  .send(msg)
  .then(() => console.log('Mail sent successfully'))
  .catch(error => console.error(error.toString()))
});

app.get('*', (req, res) => {
  res.sendFile(path.join(publicPath, 'index.html'));
});

app.listen(port, () => {
  console.log('Server is up');
});

#2

I have a react setup using sendgrid i am working on. Some of my code is here but i am using a different sort of setup.

One thing I would think about is setting up a form using state in react. Instead of using the method and submit style. You could use the npm package axios to send the POST.

Also, if you are using Create React App you could look into this.

It is hard to narrow down the exact problem without all the code. Good Luck.


#3

Thanks a lot for info! Previous part I already figured out and got it to work within my express server and now moved on to figuring out how to get fetch API working in my react app, so page doesn’t refresh every time someone submits the form.