简体   繁体   中英

React/Node js app works in development but not in production. Keep getting "POST https://phlatt.herokuapp.com/send 404 (Not Found)" Error

This app is in my github ( https://github.com/CSTy28/PhlattMusic ).

The goal was to make a contact form and automatically send an email to myself when the send button was pressed pulling the information from the form on the front end.

The only components involved in the server are contact.js in the components folder and index.js in the server folder. This is my code for contact.js using axios to post to the server:

import {useState, useEffect} from 'react';
import axios from 'axios';


function Contact() {

    const [state, setState] = useState({
        name: '',
        email: '',
        message: ''
    });

    const [result, setResult] = useState(null);

    const onInputChange = event => {
        //var name = event.target.name;
        //var value = event.target.value
        const {name, value} = event.target
    
        setState({
          ...state,
          [name]: value
        });
        console.log(state)
      };

    const sendEmail = event => {
        event.preventDefault();
        axios
            .post('/send', { ...state })
            .then(response => {
                setResult(response.data);
                setState({ name: '', email: '', subject: '', message: '' });
            })
            .catch(() => {
                setResult({ success: false, message: 'Something went wrong. Try again later'});
            });
    }
    



    



    function scroll (){
        console.log(window.scrollY)
        if (window.scrollY > 2000) {
            var citems = document.querySelectorAll('.contact-item');
            citems.forEach(inp => inp.classList.add('active'))
        }
      }
    
        window.addEventListener('scroll', scroll)

    return (
        <section className='contactSection' id='contact-me'>

            <div>
                <h1 className='contact-item c-item1'>Contact Me</h1>
            </div>

            {result && (
        <p className={`${result.success ? 'success' : 'error'}`}>
          {result.message}
        </p>
      )}
            
            <form onSubmit={sendEmail}>
                <div className='contact-item c-item2'>
                    <input type='text' name='name' placeholder='Name' onChange={onInputChange} ></input>
                </div>
                <div className='contact-item c-item3'>
                    <input type='email' name='email' placeholder='Email Address' onChange={onInputChange} ></input>
                </div>
                <div className='contact-item c-item4'>
                    <textarea type='text' name='message' placeholder='Message' cols='60' rows='10' onChange={onInputChange} ></textarea>
                </div>
                <button className='contact-item c-item5' type='submit'>SEND</button>
                
                
            </form>
            
        </section>
    )
}

export default Contact

This is the code for the backend using express to get the information from the form on the front end. In develompent everything works but on my phlatt.herokuapp.com site I get an error.

const sgMail = require("@sendgrid/mail");
const dotenv = require('dotenv');
dotenv.config();

sgMail.setApiKey(process.env.SENDGRID_API_KEY);

const path = require('path');
const express = require('express');
const transporter = require('./config');
//const dotenv = require('dotenv');
//dotenv.config();
const app = express();


const buildPath = path.join(__dirname, '..', 'build');
app.use(express.json());
app.use(express.static(buildPath));

app.post('/send', (req, res) => {
  console.log(req.body)
  const msg = {
    to: req.body.email,
    from: "CSTyy28@gmail.com",
    subject: "Confirmation",
    text: req.body.message,
    html:`
        <p>You have a new contact request.</p>
        <h3>Contact Details</h3>
        <ul>
          <li>Name: ${req.body.name}</li>
          <li>Email: ${req.body.email}</li>
          <li>Subject: "Confirmation"</li>
          <li>Message: ${req.body.message}</li>
        </ul>`
  };

  sgMail.send(msg).then(() =>  {
    console.log('Message sent')
  }).catch((error) => {
    console.log(error.response.body)
    // console.log(error.response.body.errors[0].message)
  })
  
});



app.listen(443, () => {
  console.log('server start on port 4000');
});

The docs say to follow a few command lines to hide your api key. I am convinced that is root cause of your problem. Simply placing REACT_APP_SENDGRID_API_KEY=YOUR_API_KEY in the.env file would work great for heroku as long as the config on heroku was set up with the same info. In other words there is conflict from heroku to the way sendGrid stores the env variable....On lighter note I couldn't even get my nodejs to send the email cause various hoops that were not covered in the docs so I am going to use emailjs...sendGrid for the birds.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM