Cant retrieve laravel post data with json - php

I cant retrieve json post data using fiddler
POST http://localhost/backend/login HTTP/1.1
User-Agent: Fiddler
Host: 192.168.0.147
content-type: application/json
Content-Length: 278
{
'name': 'Phill Sparks',
'location': 'England',
'skills': [
'PHP',
'MySQL',
'Laravel'
],
'jobs': [
{
'org': 'Laravel',
'role': 'Quality Team',
'since': 2012
}
]
}
routes:
Route::post('backend/login', 'UserController#backendLogin');
controller:
public function backendLogin()
{
//Input::all() and Input::json()->all() are empty
}
anything missing here?

You need to replace you single quotes ('England') with double quotes ("England") to have a valid JSON payload. You need to do this for both the keys and the values.

Related

Why does simple PHP server not print or receive POST data?

I'm running a PHP server on command line with
php -S localhost:8000 index.php
and the contents of the server are
<?php
require 'vendor/autoload.php';
use Embed\Embed;
$embed = new Embed();
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
flush();
ob_flush();
echo $_POST;
print($_POST);
var_dump($_POST);
// Prepare the response
$response = [
'status' => 'success',
'message' => 'why does this not reach you',
];
// Return the response as JSON
echo json_encode($response);
} else {
// Return an error response if the request method is not POST
$response = [
'status' => 'error',
'message' => 'Invalid request method. POST request expected.',
];
echo json_encode($response);
}
?>
The command line does react when requests come in like so:
[Fri Feb 3 18:11:47 2023] PHP 8.2.1 Development Server (http://localhost:8000) started
[Fri Feb 3 18:11:48 2023] 127.0.0.1:54363 Accepted
[Fri Feb 3 18:11:48 2023] 127.0.0.1:54363 Closing
but it says "Closing" almost immediately after the request comes in, and I can't get the contents of the request to print using echo, print, or var_dump. The client does get a response back but it looks like garbage:
{"_bodyBlob": {"_data": {"__collector": [Object], "blobId": "A4EEE117-0E46-46B3-9BA9-519F6B27357B", "name": "Unknown", "offset": 0, "size": 0, "type": "text/html"}}, "_bodyInit": {"_data": {"__collector": [Object], "blobId": "A4EEE117-0E46-46B3-9BA9-519F6B27357B", "name": "Unknown", "offset": 0, "size": 0, "type": "text/html"}}, "bodyUsed": false, "headers": {"map": {"connection": "close", "content-type": "text/html; charset=UTF-8", "date": "Sat, 04 Feb 2023 02:07:35 GMT", "host": "localhost:8000", "x-powered-by": "PHP/8.2.1"}}, "ok": true, "status": 200, "statusText": "", "type": "default", "url": "http://localhost:8000/"}
And I'm sending the request with React Native:
9 function getThumbnail(url){
8 fetch('http://localhost:8000/', {
7 method: 'POST',
6 headers: {
5 'Accept': 'application/json',
4 'Content-Type': 'application/json',
3 },
2 body: JSON.stringify({
1 data: url
0 })
1 })
2
3 .then((response) => {
4 console.log(response);
5 })
6 .catch((error) => {
7 console.error("got an error");
8 console.error(error);
9 });
10 }
I'm not sure what's going on because the server receives the request but doesn't seem to get any data from it, closes the connection immediately, and sends back a response that looks like garbage. Also haven't done much with PHP before so sorry if I'm missing something super basic.
I tried changing the server to print the contents of GET requests with print(implode($_GET)) and to navigate to localhost:8000 in my browser, but the contents of $_GET are empty as well:
Received GET request:
Looks like you are sending raw json data
Try something like this
$body = json_decode(file_get_contents('php://input'), true);
print_r($body );

Method Not Allowed on API Search

I'm using Vue.js and Laravel in combination with Axios to make a search filter for my records. When I make the request, I get the following error in my console.
GET http://localhost:8000/api/quests/search/?keywords=test 405 (Method
Not Allowed)
Vue.js
export default {
data() {
return {
quests: [],
quest: {
id: '',
name: '',
price: '',
},
keywords: null,
}
},
watch: {
keywords(after, before) {
this.fetchSearch();
}
},
methods : {
fetchSearch() {
axios.get('/api/quests/search', { params: { keywords: this.keywords}}, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => console.log(res.data))
// data empty
.catch(error => console.log(error));
}
}
API route
Route::get('quests/search', 'CrudsController#search');
Controller
public function search(Request $request)
{
$quests = Quest::where('name', 'like', $request->keywords)->get();
return QuestResource::collection($quests);
}
Network response
Cache-Control: no-cache, private
Connection: close
Content-Type: application/json
Date: Mon, 03 Dec 2018 16:08:05 +0000
Date: Mon, 03 Dec 2018 16:08:05 GMT
Host: localhost:8000
X-Powered-By: PHP/7.2.10
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
What am I doing wrong here?
You might be missing csrf token.
Try adding it to your header
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
Or you could alternatively exclude this route vie adding it to $exclude array on csrf middleware.

Laravel 5.4 Passport: unsupported_grant_type

Hello I try to do a web application and I have a problem.
When I request the token from /oauth/token I receive this response:
{"error":"unsupported_grant_type","message":"The authorization grant type is not supported by the authorization server.","hint":"Check the `grant_type` parameter"}
And my code is:
import { Injectable } from '#angular/core';
import { Http, Response, RequestOptions, Headers } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
#Injectable()
export class UserService {
private API: string = 'api/';
private OAuth: string = 'oauth/'
constructor(private _HTTP: Http) { }
private get_header(): RequestOptions {
let headers = new Headers();
headers.append('Access-Control-Allow-Origin', '*' );
headers.append('Content-Type', 'application/x-www-form-urlencoded' );
return new RequestOptions({ headers: headers });
}
Signin(email: string, password: string): void {
let data = {
form_params: {
grant_type: 'password',
client_id: 2,
client_secret: 'vSFxVqALQHjyotPyGfhrGj3ziudUGsts2ZWiAGms',
username: email,
password: password,
scope: '*',
}
};
this._HTTP.post(
this.OAuth + 'token',
data,
this.get_header()
).toPromise()
.then( (_response) => {
console.log (_response);
});
}
}
And the request header:
POST /oauth/token HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:54.0) Gecko/20100101 Firefox/54.0
Accept: application/json, text/plain, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://localhost:8000/signin
Access-Control-Allow-Origin: *
Content-Type: application/json
X-XSRF-TOKEN: eyJpdiI6IkxtOHhqd0RDUW9MVjl1YVh0U0c4N2c9PSIsInZhbHVlIjoiUmdrenlLWll2eEFtdGFQK2dsWGN0Nm5jWGY2MW5HXC9zMDJFdU52SEh4RUoxSkY1QWVHUFNySXFkUUQ3SDNaTW0zNll6SVRONlFHQjBFVzZPT0RxQkR3PT0iLCJtYWMiOiIwNzg5ZjliMzUwYjE5ZWM4MWE3MTg3NDRjYWZiMDE1MWI1NWJjN2E1NmI5ZTMzY2UzMTIwODI4ODY0ZDQ1ZDY5In0=
Content-Length: 208
Cookie: XSRF-TOKEN=eyJpdiI6IkxtOHhqd0RDUW9MVjl1YVh0U0c4N2c9PSIsInZhbHVlIjoiUmdrenlLWll2eEFtdGFQK2dsWGN0Nm5jWGY2MW5HXC9zMDJFdU52SEh4RUoxSkY1QWVHUFNySXFkUUQ3SDNaTW0zNll6SVRONlFHQjBFVzZPT0RxQkR3PT0iLCJtYWMiOiIwNzg5ZjliMzUwYjE5ZWM4MWE3MTg3NDRjYWZiMDE1MWI1NWJjN2E1NmI5ZTMzY2UzMTIwODI4ODY0ZDQ1ZDY5In0%3D; laravel_session=eyJpdiI6ImlrdlNMTGtTK241WVArZGx6MzE5Mnc9PSIsInZhbHVlIjoiRVQxSmlpZFwvV3B4eVRHVUdVYlRtY1VOZHUzZ09FQnMyZjhjSnZoQjA0VVBvM0x5YnJJbmx3b25cL3dCbVZScTVUb2lTVkg5Sldyd3R0aFluMDBvcmhxQT09IiwibWFjIjoiZDk4NjZkMDhiNTE0NzA3YzQxODVkNGJjN2E3OTRjNWEzMjc2Njk2ZjEyODY2MzY3NmRhYzAzN2U1NGE0ZTg4NCJ9
Connection: keep-alive
Response header:
HTTP/1.1 400 Bad Request
Host: localhost:8000
Connection: close
x-powered-by: PHP/7.1.1
Content-Type: application/json
Cache-Control: no-cache, private
Date: Thu, 27 Jul 2017 09:35:53 +0000, Thu, 27 Jul 2017 09:35:53 GMT
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 59
Post data:
{
"form_params": {
"grant_type": "password",
"client_id": 2,
"client_secret": "vSFxVqALQHjyotPyGfhrGj3ziudUGsts2ZWiAGms",
"username": "fasfa",
"password": "fasfa",
"scope": "*"
}
}
I don't have any other detail.
You need to install a password client for Passport. Assuming you've installed and configured Passport, to generate a password client, run:
php artisan passport:client --password
Make sure to use the details from the output of this command in your API requests.
inside form-data in postman use following
grant_type : password
client_id : 2
client_secret : vSFxVqALQHjyotPyGfhrGj3ziudUGsts2ZWiAGms or whatever this is
username: myemail#yahoo.com
password: mypassword
scope:
You can get client id and secret from oauth_clients table if no data there use following command to create a client
php artisan passport:client --password
use the oauth_clients table particular row, where password client column value is 1
see how i have integrated token generation code with login. I used right format to solve grant issue in laravel 5.8
public function login(Request $request) {
if (Auth::attempt(['email' => request('email'), 'password' => request('password')])) {
$user = Auth::user();
if(Auth::check()) { // check whether user exist
$req = Request::create('/oauth/token', 'POST',[
'grant_type' => 'password',
'client_id' => 2,
'client_secret' => 'WDv6wrY9Tf9HuixaiQjDWGy7yBqEG1IrmsLucAUI',
'username' => request('email'),
'password' => request('password'),
'scope' => ''
]);
$res = app()->handle($req);
$responseBody = json_decode($res->getContent()); // convert to json object
return response()->json(['success' => $responseBody], $res->getStatusCode());
} else {
return response()->json(['error' => 'Not logged in '], 401);
}
} else {
return response()->json(['error' => 'Authentication failed '], 401);
}
}
I used the following request on Fiddler, it worked fine :
check the header Content-Type:
'Content-Type': 'application/json'

POST request through Guzzle php

hi i wanted to make a post request to dropbox.i found there is this guzzle which can be easily send http req using php. here the http code given by dropbox
`POST /2/files/list_folder
Host: https://api.dropboxapi.com
User-Agent: api-explorer-client
Authorization: Bearer <access-token>
Content-Type: application/json
{
"path": "",
"recursive": false,
"include_media_info": true,
"include_deleted": false,
"include_has_explicit_shared_members": false
}`
This is my php code i coded for above request;
$response=$client->request('POST','https://api.dropboxapi.com',
[
'headers'=>[
'Authorization'=>'Bearer '.$API,
'User-Agen'=>'api-explorer-client',
'Content-Type'=>'application/json'
],
'form_params'=>[
'path'=>'',
'recursive'=>'false',
'include_media_info'=> 'true',
'include_deleted'=> 'false',
'include_has_explicit_shared_members'=> 'false'
]
]);
$headers = $response->getHeaders();
$body =$response->getBody();
$print=json_decode($body,true);
//Output headers and body for debugging purposes
var_dump($headers);echo"<br><br>";
var_dump($print);?>
this should give something similar to following ,but i get a small array
{"entries": [
{
".tag": "folder",
"name": "Photos",
"path_lower": "/photos",
"path_display": "/Photos",
"id": "id:bwGPfg_v6ZUAAAAAAAAAOA"
},`
what i missed here?
PS:im new to php related stuff :)
You are sending JSON, not an HTML form. So use 'json' instead of 'form_params'.

POST JSON Object with multiple headers in php

Request header
Content-Type: application/json
Authorization: Bearer [access token]
Accept: application/json
if send unicode string with message, please set Content-Type charset to UTF-8
Following is a sample request of send service.
URL-https://example.com/requests
Method - POST
Body
{
"outboundSMSMessageRequest": {
"address": [
"tel:+94771234567"
],
"senderAddress": "tel:12345678",
"outboundSMSTextMessage": {
"message": "Test Message"
},
"clientCorrelator": "123456",
"receiptRequest": {
"notifyURL": "http://128.199.174.220:1080/sms/report",
"callbackData": "some-data-useful-to-the-requester"
},
"senderName": "ACME Inc."
}
}
How to post and get responce
ajax
headers: {
'X-HTTP-Method-Override': 'POST',
'Content-Type': 'application/json'
},
or vanilla js
How to create javascript POST request to server with Headers and Data

Categories