简体   繁体   中英

Axios doen't send any data to php

I'm using axios in Reactjs to send user's data to php and then create a new user with php,but when I want to send my data it goes empty and my php side gives some error

My react codes

import React, { useReducer } from 'react';
import axios from 'axios';
import UserContext from './userContext';
import userReducer from './userReducer';

  //Register user
const registerUser = async () =>{
    const config = {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
          }
    };


    const response  = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);

    console.log(response.data);
}

return (
    <UserContext.Provider 
    value={{

        registerUser
    }}>
    {props.children}
    </UserContext.Provider>
);


}

export default UserState;


And my php side codes :

<?php
    $message = isset($_GET['message']) ? $_GET['message'] : 'no';

    $data = array ('message' => $message);

    echo json_encode($data);
?>

The result of this code is :

{message : 'no'}

You have to either change this line

$message = isset($_GET['message']) ? $_GET['message'] : 'no';

into

$message = isset($_POST['message']) ? $_POST['message'] : 'no';

or leave it as it is and send a get request by changing your axios call

from

const response  = await axios.post('http://localhost/react_cms/api/users/user.php' , {message : 'ppp'} , config);

to

const response  = await axios.get('http://localhost/react_cms/api/users/user.php?message=ppp', config);

Please note that the signature of the get method is different than the post method in Axios, as the get method does not require the data parameter.

It's considered good practice to when sending data to store you use the POST verb, whereas if you are retrieving data for a certain identifier, you may use GET.

Have a look at this documentation for explanations of http verbs that axios can utilize: https://restfulapi.net/http-methods/ .

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