【问题标题】:Statustext: undefined with status:200 using Axios to pass textinput values using react native XAMPP serverStatustext: undefined with status:200 using Axios to pass textinput values using react native XAMPP server
【发布时间】:2019-07-09 21:10:39
【问题描述】:

错误信息: 我似乎不明白这个警告。

"<br />
<b>Warning</b>:  Header may not contain more than a single header, new line detected in <b>/Applications/XAMPP/xamppfiles/htdocs/rest_api_myblog/api/post/create.php</b> on line <b>8</b><br />
<br />
<b>Notice</b>:  Undefined property: stdClass::$title in <b>/Applications/XAMPP/xamppfiles/htdocs/rest_api_myblog/api/post/create.php</b> on line <b>25</b><br />
<br />
<b>Notice</b>:  Undefined property: stdClass::$author in <b>/Applications/XAMPP/xamppfiles/htdocs/rest_api_myblog/api/post/create.php</b> on line <b>27</b><br />
<br />
<b>Notice</b>:  Undefined property: stdClass::$category_id in <b>/Applications/XAMPP/xamppfiles/htdocs/rest_api_myblog/api/post/create.php</b> on line <b>28</b><br />
<br />
<b>Warning</b>:  strip_tags() expects parameter 1 to be string, object given in <b>/Applications/XAMPP/xamppfiles/htdocs/rest_api_myblog/models/Post.php</b> on line <b>99</b><br />
{"message":"Post Created"}"

Axios

 onCreate = event => {
        event.preventDefault();  
        let cat_id = (this.state.cat + 1);
        const body = {
           'author' :this.state.author,
          'title': this.state.title,
          'body' : this.state.body,
          'category_id':String(cat_id)
        };
        console.log(body);
        axios.post(`http://localhost/rest_api_myblog/api/post/create.php`,{
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/x-www-form-urlencoded'
         }, 
        body})
        .then(res => {console.log(res)
        })
        .catch(e => console.log(e));
      }

当我使用 POSTMAN 发布时没有一个错误,但我立即从前端尝试。我收到带有上述警告的“已创建帖子”,除了日期和 ID(自动增量)之外没有创建任何帖子

PHP:这是我的创建函数

public function create(){
    //create query
    $query ='INSERT INTO '. $this->table .' SET title = :title,body = :body, author = :author, category_id = :category_id';

       //prepare statement 
       $stmt = $this->conn->prepare($query);

       //clean data 
       $this->title = htmlspecialchars(strip_tags($this->title));
       $this->body = htmlspecialchars(strip_tags($this->body));
       $this->author = htmlspecialchars(strip_tags($this->author));
       $this->category_id = htmlspecialchars(strip_tags($this->category_id));
        //bind data 
        $stmt->bindParam(':title', $this->title);
        $stmt->bindParam(':body', $this->body);
        $stmt->bindParam(':author', $this->author);
        $stmt->bindParam(':category_id', $this->category_id);

        // Execute query 
        if($stmt->execute())
            {
                return true;
            }
        // Print error if something goes wrong 
        printf("Error: %s.\n", $stmt->error);
        return false;
}

API:Create.php

<?php

// Headers 
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
//add more for creating  a post 
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Access-Control-Allow-headers,
Content-Type, Access-Control-Allow-Methods,
Authorization, X-Requested-with');

include_once '../../config/Database.php';
include_once '../../models/Post.php';

//Instantiate DB & connect
$database = new Database();
$db =$database->connect();

//initiate blog post object
$post = new Post($db);

//we need to get the data was posted 
//Get the raw posted data 
$data =json_decode(trim(file_get_contents("php://input")));
$post->title = $data->title;
$post->body = $data->body;
$post->author = $data->author;
$post->category_id = $data->category_id;

//create post 
if($post->create()) {
    echo json_encode(
      array('message' => 'Post Created')
    );
} else{
    echo json_encode(
        array('message' => 'Post not created!')
    );
} 

【问题讨论】:

    标签: php api react-native axios


    【解决方案1】:

    当没有正确传递身体参数时,这通常很常见。我会建议你是否可以使用 fetch 代替 axios 并引入 JSON.stringify(body)。但是,我已经为您重写了代码。

        onCreate = event => {
        event.preventDefault();  
        let cat_id = (this.state.cat + 1);
        const someValue = {
           'author' :this.state.author,
          'title': this.state.title,
          'body' : this.state.body,
          'category_id':String(cat_id)
        };
    
        fetch(`http://localhost/rest_api_myblog/api/post/create.php`,
        { method: 'POST',
          headers: {
            'Accept':'application/json',
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(someValue)})
        .then(res => {console.log(res)
        })
       .catch(e => console.log(e));
       this.setState({
         author: " ", 
         title: "",
    
       });
      }
    

    【讨论】:

    • 我可以用 Axios 试试新的变化,看看它是否会起作用?
    • 嗯,这是你的选择。 Fetch API 具有高度的特异性,有助于轻松跟踪错误
    猜你喜欢
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 2021-04-01
    • 2020-08-04
    • 2020-12-20
    • 2021-03-19
    • 2015-12-15
    相关资源
    最近更新 更多