我无法获取反应形式

时间:2017-06-23 17:21:42

标签: json reactjs express post fetch-api

您好我尝试从反应中进行简单的联系,但我坚持使用fetch()方法。 这是我的代码。我不知道出了什么问题。

前端

export default class ContactForm extends React.Component<IContactFormProps, any> {

  constructor(props) {
    super(props);
    // local state
    this.state = {
      tl: new TimelineMax({paused: true, delay: 1}),
      name: "",
      email: "",
      subject: "",
      message: "",
      sent: false,
    }
    this.handleOnSubmit = this.handleOnSubmit.bind(this);
    this.handleClearForm = this.handleClearForm.bind(this);
    this.handleChange = this.handleChange.bind(this);
    this.startAnimation = this.startAnimation.bind(this);
  }

  handleOnSubmit(e) {
    console.log("ContactForm->handleOnSubmit(e).");
    e.preventDefault();

    let formData = new FormData();
    formData.append(name, this.state.name);
    console.log("formData: " + formData);

    fetch('/contact', {
      method: 'POST',
      body: formData
    })
    .then((response) => {
      console.log("response: " + response);
      console.log("response.ok: " + response.ok);
      return response.json();
    })
    .then((responseJson) => {
      console.log("responseJson: " + responseJson);
    })
    .catch((error) => {
      console.log("error from fetch: " + error);
    });

  }

  handleClearForm(e) {
    console.log("ContactForm->handleClearForm(e).");
    // e.preventDefault();
  }

  handleChange(event) {
    const target = event.target;
    const name = event.target.name;
    const value = event.target.value;

    this.setState({
      [name]: value
    });
    // console.log("event.target.value: " + event.target.value);
    // this.setState({value: event.target.value});
  }

  startAnimation() {
    console.log("ContactForm->startAnimation().");
  }

  componentDidMount() {
    this.startAnimation();
  }

  componentWillUnmount() {

  }

  render() {
    return (
        <form className="contact-form-cnt"
          onSubmit={ this.handleOnSubmit }>
          <div className="top-row">
            <input type="text" name="name" placeholder="Name"
              className="name" ref="name"
              value={this.state.name} onChange={this.handleChange}/>
            <input type="text" name="email" placeholder="Em@il"
              className="email" ref="email"
              value={this.state.email} onChange={this.handleChange}/>
          </div>
          <input type="text" name="subject" placeholder="Subject"
            className="subject" ref="subject"
            value={this.state.subject} onChange={this.handleChange}/>
          <textarea name="message" placeholder="Write Your message here."
            className="message" ref="message"
            value={this.state.message} onChange={this.handleChange}></textarea>
          <button type="submit" name="submit"
            className="submit" ref="Send"
            onClick={ this.handleClearForm }>Send</button>
        </form>
    );

  };
};

后端

'use strict';

const path = require('path');
const express = require('express');
const bodyParser = require('body-parser');
const winston = require('winston');

const distPath = path.join(__dirname, '../dist');
const indexFileName = 'index.html';
const app = express();
const PORT = process.env.PORT || 8080;

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

app.use(express.static(distPath));
app.get('*', (req, res) => res.sendFile(path.join(distPath, indexFileName)));

app.post("/contact", (req, res) => {
    try {
        console.log("mail sending succes!");
    }
    catch ( error ) {
        console.log("mail sending failure!");
    }
});

app.listen(PORT, (err) => {
    if (err) {
        winston.error(err);
        return;
    }

    winston.info(`Listening on port ${PORT}`);
});

网址:

  

http://localhost:8080/contact

和错误

POST http://localhost:8080/contact 404(未找到)

我认为它与网址有关,但我的想法不合时宜。任何sugestions?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情:

app.post("/contact", (req, res) => {
   res.json({"foo": "bar"});
});

这样你就可以设置一个json对象了。如果有效,请告诉我。