API Fetch en Laravel-token cabecera

 https://www.purocodigo.net/articulo/aprende-a-utilizar-la-api-fetch-de-javascript

https://blastcoding.com/api-fetch-en-laravel/

https://www.oscarblancarteblog.com/2017/06/08/autenticacion-con-json-web-tokens/


Publicar método ajax para Laravel con Fetch API | Vainilla JS

Tuve dificultades para encontrar un ejemplo de cómo hacer una solicitud de publicación en Laravel a través de la API de búsqueda, ya que la mayoría de los ejemplos usan jQuery solo para acortarlo.

Así que espero que esto eventualmente ayude a alguien.

Lo primero es lo primero, Laravel requiere un token para verificar la falsificación de solicitudes entre sitios . Por lo tanto, debe tener una metaetiqueta en el encabezado con el token, como se explica en la documentación de Laravel.

<meta nombre="csrf-token" content="{{ csrf_token() }}">

Luego, debe enviarlo todo junto con su método de publicación.

//Seleccione el token con getAttribute 
let token = document.querySelector('meta[name=”csrftoken”]').getAttribute('content');
//Seleccione los valores de entrada con los datos que desea enviar
let name = document.querySelector('input[name=”name”]').value;
let numero = document.querySelector('input[name=”number”]').value;
//Defina la URL de su publicación
let url = '/admin/part/store';
//Defina la redirección si es necesario
let redirigir = '/admin/part/list';
//Seleccione su formulario para borrar los datos después de una publicación exitosa
deje el formulario = document.querySelector('#addPart');

Y luego haga una llamada a la API. Algunas pruebas con contenido diferente en los encabezados me arrojaron algunos errores.

fetch(url, { 
headers: {
"Content-Type": "application/json",
"Accept": "application/json, text-plain, */*",
"X-Requested-With": "XMLHttpRequest",
"X-CSRF-TOKEN": token
},
método: 'publicación',
credenciales: "mismo origen",
cuerpo: JSON.stringify({
nombre: nombre,
número: número
})
})
.then((datos) = > {
formulario.reset();
ventana.ubicación.href = redirigir;
})
.catch(función(error) {
consola.log(error);
});
}

Sería genial tener algo de resaltado de sintaxis aquí, ¿eh?+



Example of Vanilla Javascript Fetch Post API in Laravel

javascript fetch api in laravel

I have been used to calling the AJAX request in my application via jQuery and haven’t got a chance yet to experiment with the latest fetch API of Laravel.

There can be a requirement in your application where you might need to make an AJAX call with Vanilla Javascript instead of using a library or a framework.
With the advancements in Javascript, it’s Fetch API makes it very easy to make an asynchronous HTTP request with Laravel.

For this example, consider you have an HTML button in your application, Clicking on which you want to make a POST AJAX call.

<button id="postFetchAPI">Click Me</button>

We attach the click event to this button via addEventListener method of javascript and attach a callback function to it.

document.querySelector('#postFetchAPI').addEventListener('click', onClick);

And here is the function onClick that gets invoked on clicking of the button.

  let url = '/laravel-fetch-example';
     let token = document.querySelector('meta[name="csrf-token"]').getAttribute('content');

     function onClick(){
        fetch(url, {
                headers: {
                    "Content-Type": "application/json",
                    "Accept": "application/json, text-plain, */*",
                    "X-Requested-With": "XMLHttpRequest",
                    "X-CSRF-TOKEN": token
                    },
                method: 'post',
                credentials: "same-origin",
                body: JSON.stringify({
                    name: 'Tushar',
                    number: '78987'
                })
            })
            .then((data) => {
                window.location.href = redirect;
            })
            .catch(function(error) {
                console.log(error);
            });
     }

Notice that we have defined a variable named token just before the fetch call and also we are sending it as part of our request Header. To prevent Cross-site scripting, Laravel requires you to send a token on each of the POST requests. We can solve this by including a meta element on the page.

    <meta name="csrf-token" content="{{ csrf_token() }}">

Now clicking on the button will invoke the Controller method tied to the POST URL, laravel-fetch-example if the POST URL in our example.

Now in the controller method, you can get the parameters in the request variable

    public function fetchExample(Request $request){
          $name = $request->get('name');
          $number = $request->get('number');
    } 

That’s all about making a POST Asynchronous request via javascript Fetch API in Laravel.

Comentarios

Entradas populares de este blog

Filtrando por fecha

10 videojuegos gratis para aprender JavaScript en línea

reloj obs---datetime.lua