reactjs - axios POST 请求不起作用

标签 reactjs api http-post axios lumen

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

我有一个 ReactJS 应用程序,它使用 Lumen 中构建的 API。该 API 还被 React NativeJQuery AJAX 使用,并且在两者上都能正常工作。

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

Response Headers Request Headers

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,效果很好。我尝试向虚拟 API 发送 POST 请求 https://jsonplaceholder.typicode.com/users 来自 axios,效果很好。

编辑

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

CORS中间件

<?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 前端使用。

其他信息

Console Error

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

最佳答案

问题很可能出在您的请求 header 上。至少尝试设置 Content-Type。

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

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

关于reactjs - axios POST 请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51379356/

相关文章:

api - 将 CURL 转换为 postman

ios - RestKit 对象映射 POST 响应, "CoreData: error: Failed to call designated initializer on NSManagedObject class mapping operation"

javascript - '&&' 运算符用 { this.props.children && React.cloneElement(this.props.children, { foo :this. foo}) 表示什么

javascript - React 从 ReactDOM.render 调用函数

api - 在 CrafterCMS 中,如何通过 API 发布内容?

ios - swift - 从 Reddit API 解码 JSON 响应(发表评论)

rest - 如何处理超时的 POST 请求

python - Django上传文件的正确访问器

reactjs - ReactCSSTransitionGroup 与 React 0.14 和漂亮的不变违规 : addComponentAsRefTo(. ..)

javascript - 如何使用 Jest 模拟 + Enzyme 浅层测试和/或模拟 ref 回调节点并测试 .querySelector?