简体   繁体   English

Axios 不向 php 发送任何数据

[英]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我在 Reactjs 中使用 axios 将用户的数据发送到 php,然后用 php 创建一个新用户,但是当我想发送我的数据时它变空了,我的 php 端给出了一些错误

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 端代码:

<?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或保持原样并通过更改 axios 调用发送获取请求

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.请注意, get方法的签名与 Axios 中的post方法不同,因为get方法不需要 data 参数。

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.将数据发送到存储时使用 POST 动词被认为是一种很好的做法,而如果您要检索某个标识符的数据,则可以使用 GET。

Have a look at this documentation for explanations of http verbs that axios can utilize: https://restfulapi.net/http-methods/ .查看此文档以了解 axios 可以使用的 http 动词的解释: https ://restfulapi.net/http-methods/。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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