I know there are lots of question out there with the same issue, but none of the solutions have worked for me yet.
I have a ReactJS application consuming an API built in Lumen. The API is also consumed by React Native and JQuery AJAX and works fine on both.
When I try to send a POST request with axios from ReactJS, I get a 405 Method Not Allowed error on the OPTIONS Request.
The axios request is:
const body = { username, password };
axios.post(`{$uri}/payment/api/login`, {body})
.then(res => console.log(res))
.catch(err => console.log('Login: ', err));
At first I thought this was a CORS issue, which would have been strange because my API is being consumed by a static site hosted on AWS S3 with no problems. So my CORS middleware works fine.
Than I tried using fetchAPI to call the API and that works fine. I tried to send a POST request to a dummy API https://jsonplaceholder.typicode.com/users from axios and it worked fine.
Edit
Okay so I just found out that fetchAPI sends data in application/x-www-form-urlencoded format which somehow is not subject to pre-flight requests. That should mean that there is an issue with the CORS Middleware.
CORSMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
class CORSMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Access-Control-Allow-Methods', 'HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS');
$response->header('Access-Control-Allow-Headers', $request->header('Access-Control-Request-Headers'));
$response->header('Access-Control-Allow-Origin', '*');
}
}
The exact same Middleware is also used in another API build in Lumen and consumed by Vue Front-End which uses axios.
Additional Info
GET Request works fine on my API.
Problem is most likely with your request headers. try setting Content-Type atleast.
let axiosConfig = {
headers: {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Origin": "*",
}
};
const body = { username, password };
axios.post(`{$uri}/payment/api/login`, body, axiosConfig)
.then(res => console.log(res))
.catch(err => console.log('Login: ', err));
or set the Content-Type to application/x-www-form-urlencoded
if you are expecting url encoded data in the server side
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With