CORS策略:預檢請求的回應未通過存取控制檢查:請求中缺少'Access-Control-Allow-Origin'頭部
P粉311089279
P粉311089279 2024-03-25 21:43:22
0
1
394

所以我嘗試稍微玩一下前端和後端。當嘗試從前端將資料發送到伺服器時,我得到了

從來源「http://localhost:3000」存取「http://test.localhost/login」處的XMLHttpRequest 已被CORS 政策阻止:對預檢請求的回應未透過存取控制檢查:否「 Access -Control-Allow-Origin'標頭存在於請求的資源上。

以下是我的 axios onClick 設定:

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;
    }
}

P粉311089279
P粉311089279

全部回覆(1)
P粉885035114

您是否嘗試過像這樣將本機主機 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
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!