React 和 NodeJS 之间的 Post 请求(处理响应)

时间:2021-01-06 13:16:32

标签: node.js reactjs axios nodemailer

所以我使用 nodejs 服务器将我的 react 应用程序中的联系表单信息发布到 nodemailer 中,以便我可以将电子邮件发送到我的 gmail 帐户(这很好用并且电子邮件可以通过)我的问题是我想让 React响应来自 post 请求的响应。 (IE 更改状态,然后根据该状态编译消息)。但是,当我发送电子邮件时,页面重定向以仅显示从节点发送的纯 json 消息。我怎样才能阻止这种情况发生? (这里是初学者所以请放轻松!)

表格文件:

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;

节点文件:

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}!`)
});

0 个答案:

没有答案