search

Home  >  Q&A  >  body text

CORS Policy: Response to preflight request fails access control check: 'Access-Control-Allow-Origin' header is missing from the request

So I tried to play around with the frontend and backend a little bit. When trying to send data from the frontend to the server I get

Access to XMLHttpRequest at 'http://test.localhost/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request failed access control check: No 'Access -Control-Allow-Origin' header is present on the requested resource.

Here are my axios onClick settings:

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

My axiosClient is:

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;

My cors configuration on the backend is

<?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粉311089279P粉311089279253 days ago476

reply all(1)I'll reply

  • P粉885035114

    P粉8850351142024-03-26 09:48:39

    Have you tried including the localhost IP in cors.php like this?

    'allowed_origins' => ["http://localhost:3000"]

    If this doesn't work, try using this configuration

    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => ["*"],
    'allowed_headers' => ['*'],
    'exposed_headers' => ["*"],
    'max_age' => 0,
    'supports_credentials' => false,

    and comment this line in Kernel.php, but please note that this configuration will accept requests from anywhere, so make sure your backend receives requests from your preferred allowed sources before deploying.

    \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class

    reply
    0
  • Cancelreply