J
J
Jaffyel2019-09-13 21:27:53
CORS
Jaffyel, 2019-09-13 21:27:53

Laravel: POST and GET request not working, requires Access-Control-Allow-Origin, how to fix?

In general, I rummaged through everything that is possible, set everything up, did it, and still requires a title, I don’t understand what’s happening anymore, I’m attaching screenshots, where everything is written, help, what else is missing, why doesn’t it want to work?
File controller:

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class restController extends Controller
{
    public function index()
    {
        echo "gg";
    }
}

Cors.php middleware:
namespace App\Http\Middleware;

class Cors
{
    public function handle($request, \Closure $next)
    {
        $response = $next( $request );
        $response->header('Access-Control-Allow-Origin', 'localhost');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        $response->header('Access-Control-Allow-Headers', 'Origin, Content-Type');
        return $response;
    }
}

Js file on the client side (test request in json)
window.onload = init;

function init() {
    var button = document.querySelector('#btn');
    button.addEventListener('click', async function (e) {
        e.preventDefault();
        //console.log(document.querySelector('meta[name="csrf-token"]').content);
        let url = 'http://127.0.0.1:8000/photoService/registration/create';
        let user = {
            name: 'John',
            surname: 'Smith'
        };

        let promise = await fetch(url, {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                'Accept': 'application/json',
            },
            //body: user
        });
        let result = await promise.json();
        console.log(result);
    });
}

kernel.php file
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{
    protected $middleware = [
        // ...
        \App\Http\Middleware\Cors::class,
    ];
}

web.php file (route)
<?php
Route::get('photoService/registration/create', '[email protected]')->middleware('cors');

The complete error is:
Access to fetch at ' 127.0.0.1:8000/photoService/registration/create ' from origin ' restclient.ru ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alex Wells, 2019-09-13
@Jaffyel

Well, look at what requests are sent ... I suspect that OPTIONS is sent, in response to which no header comes.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question