React前端到API的POST无法正常工作-错误400

问题描述 投票:0回答:2

我正在尝试将数据发送到我的Flask API以将数据获取到我的数据库中,但是我不断收到以下错误:OPTIONS / createUser HTTP / 1.1“ 400

Reg.js

import React, { Component } from 'react';  

class Reg extends Component {  

  constructor() {  
    super();  

    this.state = {  
      FirstName: '',  
      LastName: '',  
      Email: '',  
      Password: '' 
    }  

    this.Email = this.Email.bind(this);  
    this.Password = this.Password.bind(this);  
    this.FirstName = this.FirstName.bind(this);  
    this.LastName = this.LastName.bind(this);   
    this.register = this.register.bind(this);  
  }  

  Email(event) {  
    this.setState({ Email: event.target.value })  
  }   

  Password(event) {  
    this.setState({ Password: event.target.value })  
  }  
  FirstName(event) {  
    this.setState({ FirstName: event.target.value })  
  }  
  LastName(event) {  
    this.setState({ LastName: event.target.value })  
  }  

  register(event) {  

    fetch('http://localhost:5000/createUser', {  
      method: 'post',  
      headers: {  
        'Accept': 'application/json',  
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin':'*' 
      },  
      body: JSON.stringify({  
        "FirstName": this.state.FirstName,  
        "Password": this.state.Password,  
        "Email": this.state.Email,  
        "LastName": this.state.LastName 
      })  
    }).then(function(res){
      return res.json(); //error here
    }).then(function(data){
      console.log(data);
    }).catch((error) => {
      console.log(error);
    });
  }  

  render() {  

    return (  
      <div>  
        <form className="form" id="addItemForm">
            <input type="text"  onChange={this.FirstName} placeholder="Enter First Name"/>
            <input type="text"  onChange={this.LastName} placeholder="Enter Last Name"/>
            <input type="text"  onChange={this.Email} placeholder="Enter Email"/>
            <input type="password"  onChange={this.Password} placeholder="Enter Password"/>
            <button  onClick={this.register}  color="success" block>Create Account</button>
        </form>
      </div>  
    );  
  }  
}  

export default Reg; 

这是我的Flask API所具有的东西

@main.route('/createUser', methods=['POST', 'OPTIONS'])
def createUser():
    conn = connection()
    cur = conn.cursor()

    req = request.get_json()
    first = req.get('FirstName')
    last = req.get('LastName')
    email = req.get('Email')
    pw = req.get('Password')

    sql = "INSERT INTO User (first, last, emailAddress, password) VALUES (?, ?, ?, ?)"
    data = (first, last, email, pw)
    cur.execute(sql, data)

    conn.commit()
    cur.close()

    return 'Done', 201

我已经尝试过更改JSON格式,以防其格式错误,但没有任何改变。我还尝试了从邮递员发帖,并且从那里可以正常工作,因此我认为它是javascript。

javascript reactjs post flask-restful
2个回答
0
投票

如果使用的是Chrome,请尝试添加CORS扩展名,并且应该在后端启用CORS,例如springboot @CrossOrigin(origins="http://localhost:3000")


0
投票

这应该起作用:

import React, { Component } from "react";

class Reg extends Component {
  constructor() {
    super();
    this.state = {
      FirstName: "",
      LastName: "",
      Email: "",
      Password: ""
    };
    this.Email = this.Email.bind(this);
    this.Password = this.Password.bind(this);
    this.FirstName = this.FirstName.bind(this);
    this.LastName = this.LastName.bind(this);
    this.register = this.register.bind(this);
  }

  Email(event) {
    this.setState({ Email: event.target.value });
  }

  Password(event) {
    this.setState({ Password: event.target.value });
  }
  FirstName(event) {
    this.setState({ FirstName: event.target.value });
  }
  LastName(event) {
    this.setState({ LastName: event.target.value });
  }

  register(event) {
    fetch("http://localhost:5000/createUser", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*"
      },
      body: JSON.stringify({
        FirstName: this.state.FirstName,
        Password: this.state.Password,
        Email: this.state.Email,
        LastName: this.state.LastName
      })
    })
      .then(function(res) {
        return res.json(); //error here
      })
      .then(function(data) {
        console.log(data);
      })
      .catch(error => {
        console.log(error);
      });
  }

  render() {
    return (
      <div>
        <form className="form" id="addItemForm">
          <input
            type="text"
            onChange={(event) => this.FirstName(event)}
            placeholder="Enter First Name"
          />
          <input
            type="text"
            onChange={(event) => this.LastName(event)}
            placeholder="Enter Last Name"
          />
          <input
            type="text"
            onChange={(event) => this.Email(event)}
            placeholder="Enter Email"
          />
          <input
            type="password"
            onChange={(event) => this.Password(event)}
            placeholder="Enter Password"
          />
          <button onClick={this.register} color="success" block>
            Create Account
          </button>
        </form>
      </div>
    );
  }
}

export default Reg;
© www.soinside.com 2019 - 2024. All rights reserved.