PHP : Post routes not working, 404 not found - php

I'm using Slim framework. I've made an API with Post routes and Get routes
The Get ones are working perfectly
The Post ones are not.
this one is working when accessed via javascript or php
$app->get('/test',function(){
});
While this one return an error 404 not found when accessed
$app->post('/testpost',function(){
});
I can't figure out the problem
thank you for your help

Read the docs.
POST Route
You can add a route that handles only POST HTTP requests with the Slim application’s post() method. It accepts two arguments:
The route pattern (with optional named placeholders)
The route callback
$app = new \Slim\App();
$app->post('/books', function ($request, $response, $args) {
// Create new book
});
If you are posting your data and don't see it, that's because you're not passing any $request parameter to the callback.
The Slim's router is based on nikic/FastRoute, so if you prefer you may also refer to its docs to better understand it.

How are you testing?
Start up the PHP built in web server via php -S
and then I recommend using Curl:
curl -v -X POST http://localhost:8080/testform

Related

Method not allowed - redirect using incorrect method

I have been working on a simple Laravel Inertia Vue3 application. It has one resource route.
Route::resource('contact', \App\Http\Controllers\ContactController::class);
This provides the named routes contact.index .store .create .show .update .destroy and .edit
Nice and simple so far.
I have a useForm form variable in my Vue component with some assigned variables
let form = useForm({ ... });
I have a submit method in the same component
let submit = () => {
if(props.edit) {
form.patch(`/contact/${props.contact.id}`);
} else {
form.post(`/contact`);
}
}
Again nothing complex. The post method fires off correctly and redirects
Contact::query()->create($request->all());
return redirect()->to(route('contact.index'));
For full disclosure of the update method, please see below:
public function update(Request $request, Contact $contact): \Illuminate\Http\RedirectResponse
{
$contact->fill($request->all())->save();
return redirect()->to(route('contact.show', ['contact' => $contact]));
}
This works in the same way as store. Simple and then redirects... but it doesn't.
What happens is that it runs the patch and then calls redirect
The redirect carries the patch method through ending up with a 405 if I use the index route (declared as get). If I use back() I get the same thing. If I use the show route, it redirects in a loop because the patch route uses the same URL /contact/{contact}
I have built Laravel applications for the last 5 years and have not had an issue like this before when using a named route. Have I missed something basic? If not its possibly a configuration issue although I am not sure what.
I am running Laravel 9.19 with webpack manually installed as its been changed to Vite on the current release. I have no Vue errors or warnings and no Laravel logs.
there is a difference between PUT and PATCH requests on laravel-level.
Please run php artisan route:list - and see which one is used in your case, There is a big chance that you using PUT, not patch :)
So good ol' Laravel got me again.
Alexander Dyriavin got me on the right course with his answer about put and patch, however, it wasn't really the solution.
The solution:
form.transform((data) => ({
...data,
_method: 'PUT' //spoof added to request
})).post(`/contact/${props.contact.id}`); //sent as a post instead
The Laravel docs allow you to spoof methods https://laravel.com/docs/5.0/routing#method-spoofing by posting them with a _method field.
Simply put, a patch or put request would have always failed with a redirect from Laravel. In the past I would have used them with Axios and handled a JSON response directly.
This time I really am answering my own question.
I was a total idiot and missed a step when setting up inertia js. I was attempting to retrieve errors with the useform method and what happened was I received nothing.
So I though I would double check the docs.
Turns out I missed adding this middleware to the web middleware group in the kernel!
\App\Http\Middleware\HandleInertiaRequests::class,
I can now use the .patch method I had before and no need for any additional code

Laravel CallBack URL cant be found

I am using Laravel and by the way new to the framework, i want to integrate a payment gateway that requires a callback url,
Route::post('qp', 'App\Http\Controllers\Api\MainAPIController#qp');
This is how i defined my route in the api.php and web.php. But unfortunately i cannot find my url which should be https://myApp.com/api/qp. What did i do wrongly.
actually below is my callback function. Am using laravel
$data = json_decode(file_get_contents('php://input'));
$user=$data->user_id;
$amounts=$data->amount;
$transaction_source=$data->funds_source;
$transaction_source=$data->funds_source;
$transaction_status=$data->status;
$reference=$data->client_ref;
$transaction_date=$data->trans_date;
$narration=$data->naration;
$charges=$data->charges;
if($transaction_status=="SUCCESS"){
}
elseif($transaction_status=="FAILED"){
}

POST request not allowed exception in lumen framework

I have started making some routes following the lumen documentation, where it shows basic GET and POST routing.
So I have tried to make some tests in order to understand how they work. While the GET method seems working as expected, the the POST router seems encounter some problems. Here below my test router:
$router->post('/foo', function ($req) {
var_dump($req); die();
});
Then I have tried to make a POST request using postman as below:
url : http://localhost:8000/foo
raw body of my request: {"key":"thisbodyrequestisdone"}
So, I would expect to see the var_dump of my body $req parameter sent via client at http://localhost:8000/foo. But it shows the message:
MethodNotAllowedHttpException
Probably I'm missing something. Can someone tell me exactly how to make a POST request in the right way within lumen? Thanks in advice.
UPDATE: below some additional screenshot while trying to use the $req->all():
In order for this to work you should type-hint the $req variable, as explained by the docs:
To obtain an instance of the current HTTP request via dependency injection, you should type-hint the Illuminate\Http\Request class on your controller constructor or method. The current request instance will automatically be injected by the service container Source
So your code should be:
$router->post('/foo', function (Request $req) {
var_dump($req); die();
});
Also make sure you import the Request class with use Illuminate\Http\Request;
MethodNotAllowHttpExeptions - to fix it:
Create .htaccess file in your project folder for example "Freelance.local/.htaccess" and just put this code there.
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]

Error in Slim 3 because of mismatch in request uri & request method

I'm using Slim 3 Framework as my backend and a small self-written frontend (jQuery). In my frontend I have ajax commands to call my REST server.
Now I'm facing the problem that I can't use DELETE on my client because it is not matching the HTTP request method (GET).
405 Method not allowed. Must be one of: GET, PUT
The official documentation says said it is not allowed by default:
If your Slim Framework application has a route that matches the
current HTTP request URI but NOT the HTTP request method, the
application invokes its Not Allowed handler and returns a HTTP/1.1 405
Not Allowed response to the HTTP client.
Now I could use GET or PUT but that is not possibly because I already have those routes declared for other actions.
Slim Application Error:
The application could not run because of the following error:
Details
Type: FastRoute\BadRouteException
Message: Static route /api/v1/folders/ is shadowed by previously defined variable route /api/v1/folders/(.*) for method GET
// Folder routes
$this->group('/folders', function () {
$this->get('[/{params:.*}]', 'FolderController:index');
$this->post('', 'FolderController:create');
$this->put('[/{params:.*}]', 'FolderController:update');
$this->delete('/[/{params:.*}]', 'FolderController:delete');
})->add('AuthenticateMiddleware');
Could you please give me an advice on how to solve this? Isn't this a general problem in the REST-world so to speak, because I guess many frameworks act like Slim 3 and throw a 405 Method not allowed error in such particular situation where you want to use DELETE but can't because the click in the browser is GET?
As per my comment:
Is the failing request happening when you click on a link? <a></a> ? The request method has to be DELETE in order for Slim to invoke the right controller. Also note that your delete route has an extra [
Good luck !

NotFoundHttpException in RouteCollection when routing with additional controller in laravel 5.2

I got this error-->'NotFoundHttpException in RouteCollection.php line 161'..When i try to call my additional controller in laravel 5.2..Already I did php artisan serve to activate localhost:8000..can you please explain the basic layout of routing with controller in laravel?
NotFoundHttpException occurs when no given route is matched to your given request to a certain endpoint/url.
Make sure you are sending the request to the correct url which is correctly defined in your routes.php (web.php for laravel 5.3+) with it's correct verb, (GET, POST, PATCH, etc).
Basic flow goes like this:
In your routes.php, you'd define a route like:
Route::get("/users", "UsersController#show");
then in your Http folder define that given controller with it's name which you referred in above call and anything proceeding # symbol is a callback function which gets called automatically.
So in your http/UsersController.php, you'd have:
public function show(Request $request) {
//Do something with your request.
return "Something"; //could be an array or string or
//whatever since laravel automatically casts it into JSON,
//but it's strongly recommended to use transformers and compact method.
}
For more information try looking at laravel docs, they provide an amazing way to get started tutorial. Laravel Docs

Categories