javascript - 未处理的拒绝(类型错误): Failed to fetch (POST) react/node/express

标签 javascript node.js reactjs express fetch-api

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

我现在尝试在客户端上使用 React 来实现表单,但是当我尝试 POST 时,我总是收到错误:未处理的拒绝(类型错误):无法获取

这是我的代码:

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 block 来实际调用您的 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);
      });
  };

关于javascript - 未处理的拒绝(类型错误): Failed to fetch (POST) react/node/express,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61011609/

相关文章:

javascript - 使用 immutable.js 时如何将 update 更改为 updateIn

image - Node.js, Canvas : Image given has not completed loading

reactjs - Webpack 在 '91% additional asset processing' 期间卡住

javascript - React jsx 第一个选项卡在切换后中断

javascript - 将 firebase 数据库值插入新数组

javascript - 使用 ajax 无法在灯箱中打开图像

javascript - Mocha promise 测试超时

node.js - 异步每个运行得快吗?

javascript - react 将 Prop 从子级传递给父级未定义

php - 处理大格式输入中的 "Kill"