Есть ли способ исправить сеть 204 Нет содержимого с Restful API в ReactJS - PullRequest
0 голосов
/ 26 мая 2020

Я пытаюсь создать простую контактную форму с помощью restful api и reactjs.

Когда я нажимаю кнопку отправки в инспекторе, я вижу два запроса.

Первый:

Request URL: http://wwww.localhost:4000/api/v1/
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:4000
Referrer Policy: no-referrer-when-downgrade

Второй:

Request URL: http://wwww.localhost:4000/api/v1/
Request Method: OPTIONS
Status Code: 204 No Content
Remote Address: [::1]:4000
Referrer Policy: no-referrer-when-downgrade

За 3 недели я видел только один запрос на вкладке сети в инспекторе с 200 OK.

My App. js файл выглядит так:

import React, { Component } from 'react';
import axios from 'axios';


class Contact extends Component {

    state = {
        name: '',
        message: '',
        email: '',
        username: '',
        password: '',
        sent: false,
        buttonText: 'Send Message'
    }

    formSubmit = (e) => {
        e.preventDefault()

        this.setState({
            buttonText: '...sending'
        })

        let data = {
            name: this.state.name,
            email: this.state.email,
            message: this.state.message,
            username: this.state.username,
            password: this.state.password
        }

        axios.post("http://wwww.localhost:4000/api/v1/", data)
        .then( res => {
            this.setState({ sent: true }, this.resetForm())
        })
        .catch( () => {
          console.log('Message not sent')
        })
      }

      resetForm = () => {
        this.setState({
            name: '',
            message: '',
            email: '',
            buttonText: 'Message Sent'
        })
    }

    render() {
        return(
          <form className="contact-form" onSubmit={ (e) => this.formSubmit(e)}>
          <label className="message" htmlFor="message-input">Your Message</label>
          <br/>
          <textarea onChange={e => this.setState({ message: e.target.value})} name="message" className="message-input" type="text" placeholder="Please write your message here" value={this.state.message} required/>
          <br/>
          <label className="message-name" htmlFor="message-name">Your Name</label>
          <br/>
          <input onChange={e => this.setState({ name: e.target.value})} name="name" className="message-name" type="text" placeholder="Your Name" value={this.state.name}/>
          <br/>
          <label className="message-email" htmlFor="message-email">Your Email</label>
          <br/>
          <input onChange={(e) => this.setState({ email: e.target.value})} name="email" className="message-email" type="email" placeholder="your@email.com" required value={this.state.email} />

          <div className="button--container">
              <button type="submit" className="button button-primary">{ this.state.buttonText }</button>
          </div>
        </form>
        );
    }
}

export default Contact;

Мой Api. js файл выглядит так:

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');
const cors = require('cors');

const app = express();

const port = 4000;

app.use(cors());

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.get('/', (req, res) => {
  res.send('Welcome to my api');
})

app.post('/api/v1/', (req,res) => {
  const { body: { username, password }} = req;
  const params = req.params;
  console.log(params)
  var data = req.body;

var smtpTransport = nodemailer.createTransport({
  service: 'Gmail',
  port: 465,
  auth: {
    user: 'email@gmail.com',
    pass: 'passwordEmail'
  }
});

var mailOptions = {
  from: data.email,
  to: 'pizhevsoft@gmail.com',
  subject: 'New Request',
  html: `<p>${data.name}</p>
          <p>${data.email}</p>
          <p>${data.message}</p>`
};

smtpTransport.sendMail(mailOptions,
(error, response) => {
  if(error) {
    res.send(error)
  }else {
    res.send('Success')
  }
  smtpTransport.close();
});

})

app.listen(port, () => {
  console.log('We are live on port 4000');
});

Итак, я не знаю, что означает 204 Нет содержимого .. но электронная почта не приходит ..

Могу я подсказать, как решить эту проблему ..?

1 Ответ

1 голос
/ 28 мая 2020

запрос "параметров" посмотрите на этот ответ Как отфильтровать (скрыть) предполетные запросы в моей сети Dev Tools

но ваша проблема живет здесь

...
  formSubmit = (e) => {
        e.preventDefault()

        this.setState({
            buttonText: '...sending'
        })

        const body = JSON.stringify({
            name: this.state.name,
            email: this.state.email,
            message: this.state.message,
            username: this.state.username,
            password: this.state.password
        })

       return axios.post("http://wwww.localhost:4000/api/v1/", {data: body})
        .then(() => this.setState({ ...this.resetForm(), sent: true }))
        .catch(console.log)
      }

      resetForm = () => ({
            name: '',
            message: '',
            email: '',
            buttonText: 'Message Sent'
        });
...

тоже немало проблем на спине

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...