API返回400 Bad Request响应

时间:2016-10-08 16:56:33

标签: api laravel laravel-5.2

我已经构建了一个API和一个使用该API的应用程序。一切正常,但现在,由于某种原因,我得到400 Bad Request响应。我不确定我是否在代码中更改了某些内容,因此我想仔细检查它是否正确。

所以我的API调用就是这个

$client = new GuzzleHttp\Client();

$jsonData = json_encode($data);

$req = $client->request('POST', 'https://someurl.com/api/v1/createProject', [
    'body' => $jsonData,
    'headers' => [
        'Content-Type' => 'application/json',
        'Content-Length' => strlen($jsonData),
    ]
]);

$output = $req->getBody()->getContents();

API正确设置了使用post的路由。它调用的函数是正确的,我已将其更改为测试,只需返回

return response()->json(["Success", 200]);

当我在Postman中测试API时,我可以看到返回Success。当我在我构建的其他应用程序中测试API时,我甚至在控制台中看不到POST请求,我只是显示了Laravel错误400 Bad Request。

这个问题可能是什么原因?

由于

更新

我已将请求更改为此

$data= json_encode($data);

$req = $client->post('https://someurl.com/api/v1/createProject', [
    'body' => $data
]);

如果我在编码后输出$data,我会得到类似的内容

{
    "projectName":"New Project",
    "clientName":"Test Client",
}

在被调用的API的控制器功能中,我只是做

return response()->json(['name' => $request->input('clientName')]);

400错误现在已经消失,但我现在将null返回给我

{#326 ▼
  +"name": null
}

正在将请求注入到函数中。我应该以不同的方式返回数据吗?

由于

2 个答案:

答案 0 :(得分:1)

可能你做了$ composer update并且Guzzle更新了。

因此,如果您使用的是最新的Guzzle(guzzlehttp / guzzle(6.2.2)),请执行 POST 请求:

$client = new GuzzleHttp\Client();

$data = ['name' => 'Agent Smith'];

$response = $client->post('http://example.dev/neo', [
    'json' => $data
]);

需要指定标题。

要阅读回复,请执行以下操作:

$json_response = json_decode($response->getBody());

我的完整示例(在路线文件 web.php routes.php

Route::get('smith', function () {
    $client = new GuzzleHttp\Client();

    $data = ['name' => 'Agent Smith']; 

    $response = $client->post('http://example.dev/neo', [
        'json' => $data,
    ]);

    $code = $response->getStatusCode();
    $result = json_decode($response->getBody());

    dd($code, $result);
});

    Route::post('neo', function (\Illuminate\Http\Request $request) {
        return response()->json(['name' => $request->input('name')]);
    });

或者您可以使用以下(缩短),但上面的代码是"更短"

$json_data = json_encode(['name' => 'Agent Smith']);

$response = $client->post('http://example.dev/neo', [
    'body' => $json_data,
    'headers' => [
        'Content-Type' => 'application/json',
        'Content-Length' => strlen($json_data),
    ]
]);
  

注意:如果您正在运行 PHP5.6 ,请在php.ini中将always_populate_raw_post_data更改为-1(或取消注释该行)重启你的服务器。阅读更多here

答案 1 :(得分:0)

就我而言,我应该使用BASE_URL中的公共IP地址,而我本应该使用私有IP。在Mac上,您可以通过进入系统偏好设置->网络来获取IP。

这与Android + Laravel(API)一起使用