I am using the HttpFoundation in my small project: use \Symfony\Component\HttpFoundation\JsonResponse as JsonResponse;
Unfortunately all my responses (tried JsonResponse, Response and BinaryFileResponse) only return a blank page, no errors and the code gets executed normally, e.g.
/* Get Inputs */
if (!$data = filter_input(INPUT_GET, 'url', FILTER_VALIDATE_URL)) {
return new JsonResponse(array(
'result' => 'error',
'message' => 'URL is invalid or missing'
));
}else{
return new JsonResponse(array(
'result' => 'success',
'message' => 'FINE'
));
There are no errors in the logs either.
Any ideas how to approach the issue?
//UPDATE FOR CLARIFICATION
$json = new JsonResponse(array(
'result' => 'error',
'message' => 'Encrypt is invalid or missing'
));
echo $json;
returns HTTP/1.0 200 OK Cache-Control: no-cache Content-Type: application/json {"result":"error","message":"Encrypt is invalid or missing"}
but why does the return not work?
You're not using the full stack framework, so you need to be sure that your front controller or equivalent calls $response->send(); to deliver the response to the client.
It's addition to answer:
$response = new JsonResponse(array(
'result' => 'error',
'message' => 'Encrypt is invalid or missing'
));
$response->send();
Related
I am valdating the fields sent through api and need to display the errors.
I tried using try and catch no errors thrown. I have already have a code validating the login
try {
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
'remember_me' => 'boolean',
]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
I found no errors return has json instead it is redirecting to the login page
How to handle rerros in API and sent the message as json?None of the example show the way to handle errors. I tried with everything
And also how to handle errors while creating the model
try {
$company = Company::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'country_code' => $data['country_code']]);
} catch (Exception $e) {
return response()->json(['error' => $e->getMessage()], 500);
}
$request->validate() should automatically return a response to the browser with errors if it fails, it doesn't throw an exception.
If your request is json it should detect that and return the error in a json error response, you can catch this in your front-end javascript and interrogate the response to interpret the error message.
e.g. using axios:
this.$axios.post('your api url',{data})
.then(response=>{
// ALL Good
})
.error(error=>{
// Catch returned error and process as required
});
If as you say I found no errors return has json instead it is redirecting to the login page this probably means that Laravel thinks that the request is a standard request, in which case it will issue a response()->back()->withErrors() which is probably what's sending it back to your login.
Try checking the original request type and ensure it's json, it should have a header of Accept: application/json.
Alternatively you can define your own validator
https://laravel.com/docs/7.x/validation#manually-creating-validators, and process the validation on the server as you like.
If there is error into validation then it will automatilly handle by laravel. You don't need to catch exception for that. It doesn't through exception.
Look it sample function which I have used for store Region
public function createRegion(Request $request)
{
$data = $request->all();
// Create a new validator instance.
$request->validate([
'name' => 'required',
'details' => 'required'
]);
try {
$region = new Region();
$region->name = $data['name'];
$region->details = $data['details'];
$region->save();
$content = array(
'success' => true,
'data' => $region,
'message' => trans('messages.region_added')
);
return response($content)->setStatusCode(200);
} catch (\Exception $e) {
$content = array(
'success' => false,
'data' => 'something went wrong.',
'message' => 'There was an error while processing your request: ' .
$e->getMessage()
);
return response($content)->setStatusCode(500);
}
}
I have a strange problem. There is an Ajax request (POST), which sends data to the CodeIgniter 3 endpoint and everything is ok. The data is send and I can access it there, but in the PHP, when I try something like:
echo json_encode([
'success' => false,
'message' => 'Not found'
]);
- empty response
The only way to output this is to 'echo' something BEFORE that like this:
echo 1;
echo json_encode([
'success' => false,
'message' => 'Not found'
]);
1{"success":false,"message":"Not found"}
It can be a char or a bool true (which is 1 in the browser response) and it must be before json_encode.
I have tried to set up headers to the response json or html, but with no effect.
It is the same and with Postman.
Edit.
This works, too:
echo json_encode('test');
, but I need a collection.
return json_encode([
'success' => false,
'message' => 'Not found'
]);
I try to make restful with the help of Codeigniter and chriskacerguis/codeigniter-rest library
I made a feature to delete data and if it was successful it will send status 204 and response message,
so the problem is, that not return response message if with status 204 but if followed by status 200, and etc, it works properly
I test it with Postman,
and yes of course i test it on body menu
here the code :
public function index_delete()
{
$id = $this->delete('id');
if ($id === null) {
//---- working fine return the response----
$this->response([
'status' => false,
'message' => 'Provide an id!'
], REST_Controller_Definitions::HTTP_BAD_REQUEST);
} else {
if ($this->employee->deleteEmployee($id) > 0) {
//----working, but not return the response----
$this->response([
'status' => true,
'id' => $id,
'message' => 'Successfully Deleted'
], REST_Controller_Definitions::HTTP_NO_CONTENT);
} else {
//---- working fine return the response---
$this->response([
'status' => false,
'message' => 'Id is not exits!'
], REST_Controller_Definitions::HTTP_BAD_REQUEST);
}
}
}
but if I change the status HTTP_NO_CONTENT to HTTP_OK or HTTP_BAD_REQUEST or etc it working properly
and I've also tried it this way, like in Example.php on chriskacerguis-restserver but i got nothing
$message = [
'status' => true,
'id' => $id,
'message' => 'Deleted'
];
$this->set_response($message, REST_Controller_Definitions::HTTP_NO_CONTENT);
and this is my method :
public function deleteEmployee($id)
{
$this->db->delete('employees', ['id' => $id]);
return $this->db->affected_rows();
}
so the problem is in my code, the library, or postman software?
A 204 means "no content". You can't send any response data back with a 204.
https://www.rfc-editor.org/rfc/rfc7231#section-6.3.5
The 204 (No Content) status code indicates that the server has
successfully fulfilled the request and that there is no additional
content to send in the response payload body. Metadata in the
response header fields refer to the target resource and its selected
representation after the requested action was applied.
...
The server assumes that the user agent will provide
some indication of the success to its user, in accord with its own
interface, and apply any new or updated metadata in the response to
its active representation.
https://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html#sec10.2.5
The 204 response MUST NOT include a message-body, and thus is always terminated by the first empty line after the header fields.
I am posting some data from my laravel app to another plain PHP page I have on my local server. The status code returned by Guzzle says it was successful but I am unable to access it. How can I do this?
I've tried using the Post method to retrieve value but no luck
Guzzle Function:
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
echo $response->getStatusCode();
Page Receiving POST DATA:
<?php
if (!empty($_POST['amnt'])) {
echo $_POST['amnt'];
}else
echo 'not found';
?>
I expect to be able to access the amount posted via post method but nothing is yielded.
Try somthing like that .
$client = new Client();
$response = $client->request('POST', 'http://localhost/testApp/guzTest.php',
[
'form_params' => [
'amnt' => 75
],
'allow_redirects' => true
]);
$contents = $response->getBody()->getContents();
$contents = json_decode($contents,true);
return ($contents);
On page Receiving POST DATA:
Response should be like this
return response()->json([
'status' => 'SUCCESS',
'code' => '200',
], 200);
I have function return JSON
return response()->json([
'status' => 'OK',
'data' => [
'id' => $routeForecast->id,
],
])
how can I make test for this .. my laravel version is 5.1 and i used assertJson([ ]) it give me this error
***** PHPUnit_Framework_Exception: Argument #1 (No Value) of PHPUnit_Framework_Assert::assertJson() must be a string
and try seeJson it give me this error
***** Invalid JSON was returned from the route. Perhaps an exception was thrown?
how can i solve it ??
Try something like this.
// When
$response = $this->getJson( 'v1/helloWorld' );
//dd( $response ); // perhaps die and dump here to check response?
// Then
$response
->assertStatus( 200 )
->assertJson( [
'status' => 'OK',
] );