无论如何,PHP api都会发送HTTP_response_code(400)

时间:2019-09-11 15:03:12

标签: php ajax rest

我写了一个简单的PHP Crud api,无论做什么我都得到HTTP_response_code(400)

在api中,名为create.php的文件负责在数据库中插入新项目,它检查从ajax接收的数据是否不为空,如果为空,则继续进行创建,并发送HTTP_response_code(400)

但是,无论我做什么,即使数据不为空,它也始终发送HTTP_response_code(400)

我认为问题首先出在ajax上,但是在调试之后,我发现ajax实际上从表单中获取了正确的数据并发送了它。

这是我的create.php文件

$db = $database->getConnection();

$consumable = new consumable($db);

 //get json
$json = file_get_contents("php://input");
// get posted data
$data = json_decode($json);

// make sure data is not empty
if(
    !empty($data->reference) &&
    !empty($data->price) &&
    !empty($data->description) &&
    !empty($data->category_id) &&
    !empty($data->quantity)
){

    // set consumable property values
    $consumable->reference = $data->reference;
    $consumable->price = $data->price;
    $consumable->description = $data->description;
    $consumable->category_id = $data->category_id;
    $consumable->quantity = $data->quantity;
    $consumable->created = date('Y-m-d H:i:s');

    // create the consumable
    if($consumable->create()){

        // set response code - 201 created
        http_response_code(201);

        // tell the user
        echo json_encode(array("message" => "consumable was created."));
    }

    // if unable to create the consumable, tell the user
    else{

        // set response code - 503 service unavailable
        http_response_code(503);

        // tell the user
        echo json_encode(array("message" => "Unable to create consumable."));
    }
}
else{

    // tell the user data is incomplete

    // set response code - 400 bad request
   //http_response_code(400);

    // tell the user
    echo json_encode(array("message" => "Unable to create consumable. Data is incomplete."));
    echo json_encode($json);

}

这是我的ajax:

$(document).on('submit', '#create-consumable-form', function(){
    alert("submit");
    // get form data
var form=$(this).serializeObject();
var form_data=JSON.stringify(form);
console.log('a',form);
console.log(form_data);
// submit form data to api
$.ajax({
    url: "http://localhost:3000/consumable/create.php",
    type : "POST",
    contentType : 'application/json',
    data : form_data,
    success : function(result) {
        // consumable was created, go back to consumables list
     showconsumables();
    },
    error: function(xhr, resp, text) {
        // show error to console
        console.log(xhr, resp, text);
    }
});

return false;
});

填写表单并提交而不是将条目添加到数据库并发送201 OK后,它向我显示以下错误:

jquery.js:2 OPTIONS http://localhost:3000/consumable/create.php 400 (Bad Request)
send @ jquery.js:2
ajax @ jquery.js:2
(anonymous) @ create-consumables.js:87
dispatch @ jquery.js:2
v.handle @ jquery.js:2
index.html:1 Access to XMLHttpRequest at 'http://localhost:3000/consumable/create.php' from origin 'http://localhost:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

这是我的console.log

的结果
a {reference: "BT3000", price: "10", quantity: "5", description: "description", category_id: "3"}
create-consumables.js:85 {"reference":"BT3000","price":"10","quantity":"5","description":"description","category_id":"3"}

奇怪的是,当我在HTTP_response_code(400)文件中的create.php行中注释时,它是否可以正常工作,是否有人对这种行为的原因有任何了解?

3 个答案:

答案 0 :(得分:0)

尝试将header()放入您的create.php文件中:

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

答案 1 :(得分:0)

json_decode如果无法解码,则返回null。看来就是这样。可能需要先url_decode和/或stripslashes才能对其进行解码。正如艾哈迈德所说,尝试输出$data变量以及json_decodefile_get_contents("php://input");的输出,您会很快发现错误。

还要注意,!empty(0)!empty(false)返回true。因此,如果变量的值为0或false,则在这种情况下也将返回400。在您的示例中这不是问题,但以后可能会成为问题。

答案 2 :(得分:0)

该问题是由于以下事实造成的:我标头中的content-typeapplication/json,并且我使用邮递员进行测试,但将其保留为默认的content-type,即{{1 }}