关于reactjs:Axios POST请求不起作用

Axios POST request not working

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

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

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

Response

1
2
3
4
5
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中间件存在问题。

CORSMiddleware

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

namespace App\\Http\\Middleware;

use Closure;

class CORSMiddleware
{
  /**
   * Handle an incoming request.
   *
   * @param  \\Illuminate\\Http\
equest  $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


问题很可能与您的请求标头有关。尝试设置Content-Type至少。

1
2
3
4
5
6
7
8
9
10
11
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编码的数据


如果您在幼虫处使用此请求,则需要从fromData

中删除_method

1
2
const formData = new FormData(document.querySelector('form'));
formData.delete('_method');

对我来说,问题出在服务器端(Node.js)。

在应用CORS设置之前,我正在应用中间件功能(该功能检查令牌是否存在),这导致只进行OPTIONS调用。

例如

  • app.use(verifyToken);
  • require(" ./ startup / cors")(app)
  • 我取消了他们的订单,对我来说效果很好。


    在请求之前使用OPTIONS请求,以检查是否允许您从该域执行请求以及可以使用哪些标头。参见。

    此OPTIONS请求失败,因为数据和Content-Type冲突。

    您需要在请求中添加此标头:{ 'Content-Type': 'application/json' },并使用JSON.stringify函数转换数据:

    1
    2
    3
    4
    5
    6
    7
    8
    const data = JSON.stringify({ email, password });
    const options = {
      method: 'POST',
      headers: { 'content-type': 'application/json' },
      data,
      url,
    };
    axios(options);

    或者,您可以仅在请求中添加此标头:{ 'Content-Type': 'application/x-www-form-urlencoded' }

    1
    2
    3
    4
    5
    6
    7
    8
    const data = { email, password };
    const options = {
      method: 'POST',
      headers: { 'content-type': 'application/x-www-form-urlencoded' },
      data,
      url,
    };
    axios(options);

    解决方案取决于您的后端API规范。


    我遇到了这个问题,最终学习了比我想了解的更多有关COR的知识。最终,我从头开始,用我能找到的所有用于COR的开关重新创建了API,然后将代码剥离回去:

    1
    2
    3
    4
    5
    axios.post(postUrl).then(
      (res) => {
        console.log('Axios:',res);
        console.log('Axios data:',res.data);
      }).catch((err) => { console.log('Axios Error:', err); })

    像护身符一样工作。标头是服务器端必需的,而不是我的应用程序。希望对您有所帮助。