所以我嘗試稍微玩一下前端和后端。當(dāng)嘗試從前端將數(shù)據(jù)發(fā)送到服務(wù)器時(shí),我得到了
從源“http://localhost:3000”訪問“http://test.localhost/login”處的 XMLHttpRequest 已被 CORS 策略阻止:對預(yù)檢請求的響應(yīng)未通過訪問控制檢查:否“ Access-Control-Allow-Origin'標(biāo)頭存在于請求的資源上。
下面是我的 axios onClick 設(shè)置:
export const login = (email, password) => { return axiosClient.post('/login', { email, password }) .then(response => { // handle successful login return response.data; }) .catch(error => { // handle failed login throw error; }); };
我的 axiosClient 是:
import axios from "axios"; const axiosClient = axios.create({ baseURL: process.env.REACT_APP_API_URL, (my localhost) headers: { 'Content-Type': 'application/json', Accept: 'application/json', }, }); export default axiosClient;
我在后端的cors配置是
<?php namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class Cors { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse */ public function handle($request, Closure $next) { $headers = [ 'Access-Control-Allow-Origin' => 'http://localhost:3000', 'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers' => 'Content-Type, Authorization', ]; if ($request->isMethod('OPTIONS')) { return response()->json([], 200, $headers); } $response = $next($request); foreach ($headers as $key => $value) { $response->header($key, $value); } return $response; } }
您是否嘗試過像這樣將本地主機(jī) IP 包含在 cors.php 中?
'allowed_origins' => ["http://localhost:3000"]
如果這不起作用,請嘗試使用此配置
'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => ["*"], 'allowed_headers' => ['*'], 'exposed_headers' => ["*"], 'max_age' => 0, 'supports_credentials' => false,
并在 Kernel.php 中注釋此行,但請注意此配置將接受來自任何地方的請求,因此在部署之前確保您的后端接收來自您首選允許來源的請求。
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class