Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
217 views
in Technique[技术] by (71.8m points)

node.js - Post Request between React and NodeJS (handling response)

So I am using a nodejs server to post contact form information from my react app into nodemailer so that I can send emails to my gmail account (this works fine and the emails come through) My question is I want to get React to respond to the response from the post request. (IE change state and then compile a message depending on that state). However when I send an email the page redirects to show just the plain json message sent from node. How can I stop this from happening? (Beginner here so please go easy!)

FORM FILE:

import React from 'react';`enter code here`
import './form.scss';
import axios from 'axios'

class Form extends React.Component{

    constructor(){
        super();

            this.state= {
                email: "",
                topic: "",
                query: "",
                result: ""
            }

            this.handleChange = this.handleChange.bind(this);
            this.handleSubmit = this.handleSubmit.bind(this);
    }

     handleSubmit = (event)=> {

        const {email, topic, query, error, success} = this.state;
        const data ={
            email,
            topic,
            query
        };

        event.preventDefault();
      
        axios
            .post('http://localhost:5000/', data)
            .then((res) => {
                
                this.setState({result: "success"})
            })
            .catch(err => {
                console.error(err)
                this.setState({result: "fail"})
            })
        }

    handleChange = (event) => this.setState({
        [event.target.name]: event.target.value
    });
  

    
    render(){
        const {result, topic, email, query} = this.state;

        if(result === "success"){
            return(<div>YES</div>);
        }
        if(result === "fail"){
            return(<div>NO</div>);
        }
        else{
        return(
                <div>
                    <form action="/" method="POST" className="contact-form" >

                                    <label className="contact-label">Email
                                    <input type="text" name="email"  value={email} onChange={this.handleChange} />
                                    </label>

                                    <label className="contact-label">Topic
                                    <input type="text" name="topic" value={topic} onChange={this.handleChange}/>
                                    </label>

                                    <label className="contact-label">Query
                                    <textarea name="query" value={query} onChange={this.handleChange} id="" cols="30" rows="10"></textarea>
                                    </label>

                                    <button type="submit" className="submit-button" onSubmit={this.handleSubmit}>Send Email</button>

                    </form>
                </div>
            )
        }
    }  
}

export default Form;

NODEJS FILE:

const express = require('express')
const path = require('path');
const PORT = process.env.PORT || 5000;
const { body,validationResult } = require('express-validator');
const nodemailer = require("nodemailer");
const bodyParser = require('body-parser');
const app = express();
const cors = require('cors');

const { google } = require("googleapis");
const { reseller } = require('googleapis/build/src/apis/reseller');
const OAuth2 = google.auth.OAuth2;

require('dotenv').config()

app.use(express.static('public'));

app.use(bodyParser.json());

app.use(express.urlencoded({
  extended: true
}))

if (process.env.NODE_ENV === 'production'){
  app.use(express.static(path.join(__dirname, 'client/build')));

  app.get('*', function(req,res){
      res.sendFile(path.join(__dirname, 'client/build' , 'index.html'))
  })
}

app.use(
  cors({
    origin: 'http://localhost:3000',
    credentials: true,
  })
);




app.route('/')
  .post([body('email').isEmail()],(req,res) => {
    const errors = validationResult(req);
    const email = req.body.email
    const topic = req.body.topic
    const query = req.body.query
    const body = `${email} sent a message with the topic: ${topic} and content: ${query} `
  
      const myOAuth2Client = new OAuth2(
      process.env.CLIENT_ID,
      process.env.CLIENT_SECRET,
      "https://developers.google.com/oauthplayground"
      )

      myOAuth2Client.setCredentials({
        refresh_token: process.env.REFRESH_TOKEN
        });

      const myAccessToken = myOAuth2Client.getAccessToken()

      const transport = nodemailer.createTransport({
        service: "gmail",
        auth: {
             type: "OAuth2",
             user: process.env.SECRET_EMAIL, //your gmail account you used to set the project up in google cloud console"
             clientId: process.env.CLIENT_ID,
             clientSecret: process.env.CLIENT_SECRET,
             refreshToken: process.env.REFRESH_TOKEN,
             accessToken: myAccessToken //access token variable we defined earlier
        }});

      const mailOptions = {
        from: email, 
        to: process.env.SECRET_EMAIL, 
        subject: topic, 
        text: body
      };

    if (!errors.isEmpty()) {

    console.log(error)

    } else {
      transport.sendMail(mailOptions, function(error, info){
        
        if(error){
          
          res.status(400).send({message: "failed"})

        }else{
        
          res.status(200).send({message: "success"})

        };
    });
    }
  
  });


app.listen(PORT, () => {
  console.log(`Listening on port ${PORT}!`)
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...