未处理的拒绝(TypeError):无法获取(POST)反应/节点/表达

时间:2020-04-03 12:08:36

标签: javascript node.js reactjs express fetch-api

我正在尝试使用react和node / express /(mongo)作为后端构建一个Login / Register表单。 后端工作正常。当我将POST请求(带有邮递员)发送到/ register时,一切正常,并且凭据存储在数据库中。

我现在尝试通过在客户端进行反应来实现表单,但是当我尝试POST时,总是会收到错误:Unhandled Rejection (TypeError): Failed to fetch

这是我的代码:

import React, { Component } from 'react';

class Register extends Component {
  state = { email: '', password: '' };

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

  onSubmit = event => {
    event.preventDefault();
    fetch('localhost:3000/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: this.state.email,
        password: this.state.password
      })
    });
  };

  render() {
    return (
      <form onSubmit={this.onSubmit} noValidate>
        <h1>Login</h1>
        <input
          type="email"
          name="email"
          placeholder="Enter email"
          value={this.state.email}
          onChange={this.handleInputChange}
        />
        <input
          type="password"
          name="password"
          placeholder="Enter password"
          value={this.state.password}
          onChange={this.handleInputChange}
        />
        <input type="submit" value="Submit" />
      </form>
    );
  }
}

export default Register;

我们将不胜感激:)

2 个答案:

答案 0 :(得分:1)

您需要使用then块来实际调用您的api。

  onSubmit = event => {
    event.preventDefault();
    fetch("localhost:3000/register", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        email: this.state.email,
        password: this.state.password
      })
    })
      .then(res => {
        console.log("response: ", res);
      })
      .catch(err => {
        console.log("error:", err);
      });
  };

答案 1 :(得分:0)

就我而言,在“ localhost”之前插入“ http://”有效!

onSubmit = event => {
    event.preventDefault();
    fetch('http://localhost:3000/register', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        email: this.state.email,
        password: this.state.password
      })
    });
  };