Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios POST request not working

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.

Response Headers Request Headers

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

Console Error

GET Request works fine on my API.

like image 896
Haseeb Burki Avatar asked Jul 17 '18 10:07

Haseeb Burki


1 Answers

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

like image 89
waleed ali Avatar answered Sep 23 '22 13:09

waleed ali