0

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 not found

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 ?

  • You are getting a 404 response, which often means you simply targeted a non-existing URL, but since here in this instance you are mkaing your PHP script itself respond with a 404 status code if your database query failed, it might probably be the latter. So, figure out which of the two cases it is - and then debug _why_ your database query failed, if it is the latter … – CBroe Nov 13 '20 at 10:37
  • _“and my contact.php (second code) is in src/api/contact/ directory”_ - and the web root of your project points to what exactly? – CBroe Nov 13 '20 at 10:39
  • **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman Nov 13 '20 at 10:41
  • It is a very bad idea to use `die(mysqli_error($$conn));` in your code, because it could potentially leak sensitive information. See this post for more explanation: [mysqli or die, does it have to die?](https://stackoverflow.com/a/15320411/1839439) – Dharman Nov 13 '20 at 10:41
  • Hi, I'm pretty sure my php code is working good and my query don't failed when i test it, I don't have any root (First time in reactJS and PHP) how can i do that – xXx_Ninj4_Kill3r_xXx Nov 13 '20 at 10:46
  • If you are only starting to learn PHP then you need to find a better tutorial/course. Your PHP has bugs that will break your code at some point. Please find a tutorial that teaches you how to use PDO – Dharman Nov 13 '20 at 10:48
  • 2
    _“I'm pretty sure my php code is working good”_ - pretty sure is not good enough, you need to actually _verify_ things like this. That is what debugging _is_ - **making sure** that your code does what you expect it to do, not retreating on “pretty sure”. – CBroe Nov 13 '20 at 10:52
  • _“I don't have any root”_ - any project you set up on your web server, always has a root directory. _We_ can not tell from the information you have presented us so far, whether `/api/contact/contact.php` is actually the correct path to your script, or whether it might be `/src/api/contact/contact.php` instead. – CBroe Nov 13 '20 at 10:54

1 Answers1

0

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)
  });
Prime
  • 2,809
  • 1
  • 7
  • 23
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Dharman Nov 13 '20 at 10:50