PHP Post请求可以在Postman中工作,但不能在React中使用Axios

fnatzsnv  于 10个月前  发布在  PHP
关注(0)|答案(2)|浏览(77)
  • 我有一个用PHP写的服务器,它有一些路由
  • Postman 的路线很好
  • 但是当我在Axios上使用React时,它给出了错误
  • 下面是PHP代码
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: GET,POST,DELETE,OPTIONS");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");

字符串
这是我如何向Postman发出请求的这是我在Postman中输入的原始JSON数据

{
    "data1" : "data1"
}


这就是我如何使用React和Axios进行post请求

await axios("url", {
        data: JSON.stringify({ "data1" , "data1" }),
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
      });


url是相同的,但它给网络错误
我希望我的axios请求能像在postman上一样完成


的数据



我也试过这个配置,但不工作

<?php

// Allow from any origin
if(isset($_SERVER["HTTP_ORIGIN"]))
{
    // You can decide if the origin in $_SERVER['HTTP_ORIGIN'] is something you want to allow, or as we do here, just allow all
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
}
else
{
    //No HTTP_ORIGIN set, so we allow any. You can disallow if needed here
    header("Access-Control-Allow-Origin: *");
}

header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 600");    // cache for 10 minutes

if($_SERVER["REQUEST_METHOD"] == "OPTIONS")
{
    
    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_METHOD"]))
        header("Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT"); //Make sure you remove those you do not want to support

    if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))
        header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    //Just exit with 200 OK with the above headers for OPTIONS method
    exit(0);
}
//From here, handle the request as it is ok

11dmarpk

11dmarpk1#

由于您在本地运行代码,请尝试使用electronjs。它解决了CORS问题。你甚至不需要轴。

iibxawm4

iibxawm42#

OK guyz,现在我明白了问题所在,我在000webhost中托管了我的PHP API,这个主机提供商不支持OPTIONS方法,这是一个只由浏览器(而不是 Postman )发出的飞行前请求方法。这就是为什么它在Postman中工作,而不是在React中。

相关问题