我在将数据发布到生产Laravel控制器以存储本地WAMP服务器上使用Guzzle发出的发布请求时遇到麻烦。我可以通过get请求成功返回数据,但是发布数据似乎不起作用。我已经使用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();
答案 0 :(得分:0)
发布不带json_encode的数据并使用form_params代替正文
$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'
];
$header = array('Authorization' => 'Bearer '.$auth->access_token, 'Content-Type' => 'application/json');
$response = $client->post('https://www.website.com/api/store_data',
['form_params' => $data, 'headers' => $header]);
$stream = $response->getBody()->getContents();
dd($stream);
用于存储数据:
$post = $request->all();
Enquiry::create([
'first_name' => $post['first_name'],
'last_name' => $post['last_name']
]);