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

Unhandled Rejection (TypeError): Failed to fetch (POST) react / node / express

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

我现在尝试通过在客户端做出反应来实现表单,但是当我尝试 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;

帮助将不胜感激:)

您需要使用 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);
      });
  };

就我而言,在“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
      })
    });
  };