我知道有很多关于同样问题的问题,但没有一个解决方案对我有用。
我有一个 ReactJS 应用程序,它使用 Lumen 中构建的 API。该 API 还被 React Native 和 JQuery 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,效果很好。我尝试向虚拟 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 前端使用。
其他信息
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/