Axios POST 请求不起作用

新手上路,请多包涵

我知道有很多关于同样问题的问题,但没有一个解决方案对我有用。

我有一个使用 Lumen 内置 API 的 ReactJS 应用程序。该 API 也被 React NativeJQuery AJAX 使用,并且在两者上都可以正常工作。

当我尝试从 ReactJS 使用 axios 发送 POST 请求时,我在 OPTIONS 请求上收到 405 Method Not Allowed 错误。

响应标头请求标头

axios 请求是:

 const body = { username, password };

axios.post(`{$uri}/payment/api/login`, {body})
     .then(res => console.log(res))
     .catch(err => console.log('Login: ', err));

起初我认为这是一个 CORS 问题,这会很奇怪,因为我的 API 被托管在 AWS S3 上的静态站点使用,没有任何问题。所以我的 CORS 中间件工作正常。

比我尝试使用 fetchAPI 来调用 API 并且效果很好。我尝试从 axios 向虚拟 API https://jsonplaceholder.typicode.com/users 发送 POST 请求,它工作正常。

编辑

好的,所以我刚刚发现 fetchAPI 以 application/x-www-form-urlencoded 格式发送数据,这种格式不受飞行前请求的影响。这应该意味着 CORS 中间件存在问题。

CORSM中间件

<?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', '*');
   }
}

完全相同的中间件也用于 Lumen 中的另一个 API 构建,并由使用 axios 的 Vue 前端使用。

附加信息

控制台错误

GET 请求在我的 API 上运行良好。

原文由 Haseeb Burki 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 949
1 个回答

问题很可能出在您的请求标头上。至少尝试设置内容类型。

 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));

或者将 Content-Type 设置为 application/x-www-form-urlencoded 如果您希望在服务器端使用 url 编码数据

原文由 waleed ali 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题