CORS策略:预检请求的响应未通过访问控制检查:请求中缺少'Access-Control-Allow-Origin'头部
P粉311089279
P粉311089279 2024-03-25 21:43:22
0
1
516

所以我尝试稍微玩一下前端和后端。当尝试从前端将数据发送到服务器时,我得到了

从源“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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板