【发布时间】:2019-10-19 11:55:21
【问题描述】:
我在将数据发布到生产 Laravel 控制器以存储使用 Guzzle 从本地 WAMP 服务器发出的发布请求时遇到问题。我可以通过获取请求成功返回数据,但发布数据似乎不起作用。我使用 Laravel Passport 设置了 Oauth2。
以下是我来自 WAMP 服务器的 Guzzle 发布请求。
$client = new \GuzzleHttp\Client();
$response = $client->post('https://www.website.com/oauth/token', [
'form_params' => [
'client_id' => 99,
'client_secret' => '***',
'grant_type' => 'password',
'username' => 'username@mail.com',
'password' => 'password',
'scope' => '*',
],
]);
$auth = json_decode((string) $response->getBody()->getContents());
$data = [
'first_name' => 'Post', 'last_name' => 'Man',
'email' => 'postman@mail.com', 'phone' => '0400000000',
'country' => 'Internet', 'state' => 'HTTP'
];
$json_data = json_encode($data);
$header = array('Authorization' => 'Bearer '.$auth->access_token, 'Content-Type' => 'application/json');
$response = $client->post('https://www.website.com/api/store_data',
['body' => $json_data, 'headers' => $header]);
$stream = $response->getBody()->getContents();
dd($stream);
返回:
"{"attributes":{},"request":{},"query":{},"server":{},"files":{},"cookies":{},"headers":{}}"
当我尝试将数据存储在生产控制器中时,请求中没有任何内容:
$enquiry = new Enquiry;
$enquiry->first_name = $request->get('first_name');
$enquiry->last_name = $request->get('last_name');
....
$enquiry->save();
【问题讨论】:
-
不应该是
$response->getBody()->getContents()吗? -
你指的是哪一行:$stream = $response->getBody()->getContents();
-
不,我指的是
$auth = json_decode(...)。 -
为了您的请求通过您需要发送正确的
Content-Type。在这种情况下,它应该是application/json -
更新了 header 以包含 content-type,并将 getContents() 添加到 $auth,仍然没有运气。