Im testing my laravel rest API with postman, my end point only allow POST method but when i test it with GET method the body return webpage instead of json. How could i handle the response to return json although the response is 405?
You can handle it in function render of app/Exceptions/Handler.php
Ex:
public function render($request, Exception $e)
{
if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException) {
return response()->json(['message' => $e->getMessage(), 405);
}
return parent::render($request, $e);
}
The docs for it: https://laravel.com/docs/5.8/errors#render-method
I think Laravel has the response as JSON for it by default. You also can add to headers of request.
Content-Type: application/json
Accept: application/json
Related
In the Laravel documentation there is this part:
You may also dispatch a closure and chain the afterResponse method onto the dispatch helper to execute a closure after the HTTP response has been sent to the browser:
use App\Mail\WelcomeMessage;
use Illuminate\Support\Facades\Mail;
dispatch(function () {
Mail::to('taylor#example.com')->send(new WelcomeMessage);
})->afterResponse();
This works perfectly fine when the mail is successfully sent. However, when there is an error in the mail sending function, for example, if I intentionally misconfigure the mailing service credentials in .env, then Laravel appends a {"message": "Server Error" } to the response.
Here's an excerpt from the actual code:
public function register() {
try {
dispatch(function () use ($user) {
Mail::to($user)->send(new Register($user));
})->afterResponse();
} catch (Exception $e) {
return response()->json(['success' => true]);
}
return response()->json(['success' => true]);
}
When the mail succeeds, the JSON data {success: true} is returned for the ajax call to process. However, when there is an error in the mail sending part, the following message is returned:
{"success":true}{
"message": "Server Error"
}
The try-catch blocks didn't seem to help.
Any ideas why is that message appended to the response data?
Laravel Version: 5.5.14
PHP Version: 7.1.10
Description:
When I try to POST with X-Requested-With='XMLHttpRequest' without CSRF-TOKEN I receive null message in response.
I add this code to App\Exceptions\Handler:
public function render($request, Exception $exception)
{
if($exception instanceof TokenMismatchException) {
abort(419, 'Token Mismatch OR page has expired due to inactivity.');
}
return parent::render($request, $exception);
}
Now I have Token Mismatch OR page has expired due to inactivity. message in response, but status text is: unknown status.
How can I set status text?
Return a \Illuminate\Http\Response and manually set the status code:
use Illuminate\Http\Response;
// snip
public function render($request, Exception $exception)
{
if($exception instanceof TokenMismatchException) {
return (new Response)->setStatusCode(419, "Token Mismatch OR page has expired due to inactivity.");
}
return parent::render($request, $exception);
}
The Status Code is part of the HTTP Protocol. 419 is not an official status Code see: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes therefor it is unknown.
So unknown status is right.
But if you really looking for the file where this is defined, go to:
/vendor/symfony/http-foundation/Response.php
Note:
If you change this file, than you have to do this after every update again.
I have created the following function into the main Controller.
public function noContent() : JsonResponse
{
return response()->json([], Response:HTTP_NO_CONTENT);
}
When deleting some data, I am returning the above function but I get a message that "Could not get any response".
I also have tried to pass a message (even if this is not recommended for a 204) in the array but still, I receive the same error. I am using the same function to return 200 or 404 messages and there worked as expected.
Is there another solution to make this work?
You should do:
return response('', 204);
I would like to show 404 page in Laravel 5 while MethodNotAllowedHttpException throws.
Can anyone help me in this regard?
Add this to app/Exceptions/Handler.php:
public function render($request, Exception $e)
{
if ($e instanceof MethodNotAllowedHttpException)
{
abort(404);
}
return parent::render($request, $e);
}
Then edit resource/views/errors/404.blade.php to personalize the page.
Simple: all you have to do is create a template at resources/views/errors/404.blade.php.
You can create views for other HTTP status codes if you’re feeling that way inclined, such as a 403.blade.php for Forbidden exceptions and so on.
I'm working on Laravel 5.2 and the answer given here worked for me.
You need to modify the render method in the app/Exceptions/Handler.php.
public function render($request, Exception $e)
{
if ($e instanceof \Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException)
{
return response(view('errors.404'), 404);
}
return parent::render($request, $e);
}
abort(404) did not work for me. Looks like this method is removed in Laravel 5.
That's a 405 error, easiest way would be to create a new view in resources/views/errors/405.blade.php..
If you need fine control over what is displayed then you'll have to use the Handler.php to modify what's returned.
I have project on Laravel 5, and I need to do async request via jQuery's $.ajax method.
Laravel can catch exception, and then it render special error template with it's own styles and markup.
But for async requests this html-code is redundant.
Is there a way to generate error response without laravel's markup on async requests?
I guess you wanted this to write the web service.
To handle this
Goto app/Exceptions/Handler.php :
And change this function
public function render($request, Exception $e)
{
return parent::render($request, $e);
}
to
public function render($request, Exception $e)
{
if ($this->isHttpException($e))
{
return $this->renderHttpException($e);
}
else
{
return parent::render($request, $e);
}
}
Also if you need to customize in the webview
Change your 404 blade \resources\views\errors\404.blade.php here