【发布时间】:2021-10-11 04:03:58
【问题描述】:
所以我知道这里的问题是我试图从example.com 向localhost 发送一个POST 请求。我不确定为什么这不起作用,据我所知,我已经通过核选项将所有内容添加到 Laravel。
在 Laravel 中,我在 public/index.php 中添加了以下内容:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'):
我知道这不是理想的方法,但是我在使用 Cors 中间件时也遇到了同样的问题。
我的客户端是一个使用 Axios 从浏览器发送 POST 请求的 React 应用程序,在网络选项卡中我可以看到以下内容:
我的 Axios 请求如下所示:
await axios({
method: 'POST',
url: 'http://localhost:8000/api/webhooks/platform',
data: notification.data,
headers: {
Origin: 'https://example.com'
}
});
有人知道我哪里出错了吗?我的版本在下面,并且很严格。我无法更改这些:
{
"php": "^7.1.3",
"laravel/framework": "5.8.*",
"laravel/nexmo-notification-channel": "^2.5",
"laravel/tinker": "^1.0",
"nexmo/laravel": "^2.4",
}
我尝试了this answer,但我得到了Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
app/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Credentials', true)
->header('Access-Control-Allow-Headers', 'Authorization,Accept,Origin,DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range');
}
}
内核.php
protected $routeMiddleware = [
......
'cors' => \App\Http\Middleware\Cors::class,
];
routes/api.php
Route::post('/webhooks/platform', 'WebhooksController@handlePlatformNotification') -> middleware('cors');
【问题讨论】:
标签: php reactjs laravel axios cors