简体   繁体   中英

Sending data to a php file from reactJS with axios

I have a website in reactJS and I want to let my user to register in my site, so i have the code:

import React from 'react'
import axios from 'axios'
import './Style/button.css'

class Register extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            email: '',
            password: '',
            confirmPassword: ''
        }
    }

    handleFormSubmit(event) {
        event.preventDefault();

        let formData = new FormData();
        formData.append('email', this.state.email)
        formData.append('password', this.state.password)

        console.log(formData);
        axios({
            method: 'post',
            url: './api/contact/contact.php',
            data: formData,
            config: { headers: { 'Content-Type': 'multipart/form-data' } }
        })
            .then(function (response) {
                //handle success
                console.log(response)

            })
            .catch(function (response) {
                //handle error
                console.log(response)
            });
    }

    render() {
        return (
            <form className="formulaire">
                <fieldset>
                    <legend> Register : </legend>
                    <p>Mail adress :</p>
                    <input type="text" placeholder="Mail" name="email" value={this.state.email} onChange={e => this.setState({ email: e.target.value })}></input>
                    <br />
                    <p>Choose a password :</p>
                    <input type="password" placeholder="password" name="password" value={this.state.password} onChange={e => this.setState({ password: e.target.value })}></input>
                    <br />
                    <p>Confirm your password :</p>
                    <input type="password" placeholder=" confirm password" name="confirmPassword" value={this.state.confirmPassword} onChange={e => this.setState({ confirmPassword: e.target.value })}></input>
                    <br /><br /><br /><br />
                    <input className="button" type="submit" onClick={e => this.handleFormSubmit(e)} value="Sign up" />
                </fieldset>
            </form>
        );
    }
}

export default Register;

When i want to send the information with axios to my php file:

<?php
$host = "localhost";
$user = "root";
$password = "azertyuiop3104";
$dbname = "reactdb";
$id = '';

$con = mysqli_connect($host, $user, $password, $dbname);

$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'], '/'));


if (!$con) {
  die("Connection failed: " . mysqli_connect_error());
}


switch ($method) {
  case 'GET':
    break;
  case 'POST':
    $email = $_POST["email"];
    $password = $_POST["password"];

    $sql = "insert into user (username, password) values ('$email', '$password')";
    break;
}

// run SQL statement
$result = mysqli_query($con, $sql);

// die if SQL statement failed
if (!$result) {
  http_response_code(404);
  die(mysqli_error($con));
}

if ($method == 'POST') {
  echo json_encode($result);
} else {
  echo mysqli_affected_rows($con);
}

$con->close();

My request fail: 404 未找到

my file register.js (first code) is in a src/ directory and my contact.php (second code) is in src/api/contact/ directory

I don't know how to fix that, if any one can help me?

Also, make sure the port that backend is hosted is 3000.

axios({
    method: 'post',
    url: 'http://localhost:3000/api/contact/contact.php', // <---------------
    data: formData,
    config: { headers: { 'Content-Type': 'multipart/form-data' } }
})
  .then(function (response) {
      //handle success
      console.log(response)

  })
  .catch(function (response) {
      //handle error
      console.log(response)
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM