score:1

Accepted answer

you can try as:

public function save() 
{
    return response()->json(['data' => 'here']);
}

the json method will automatically set the content-type header to application/json, as well as convert the given array into json using the json_encode php function.

docs

score:1

you are almost there. you must return another promise, that gets text or json from fetch:

fetch('http://laravel.dev/content', {
    method: 'post',
    headers: {
        'accept': 'application/json',
        'content-type': 'application/json',
    },
    body: json.stringify({

    })
})
.then((response) => response.text()) //or response.json()
.then((text) => {
    console.log(text);
});

also, you need to make a cors request, otherwise you can't access the response. you'll need to add this global middleware to laravel if you want to accept ajax requests from all origins

<?php
namespace app\http\middleware;
use closure;

class cors
{
    /**
     * handle an incoming request.
     *
     * @param  \illuminate\http\request  $request
     * @param  \closure  $next
     * @return mixed
     */
    public function handle($request, closure $next)
    {
        return $next($request)
            ->header('access-control-allow-origin', '*')
            ->header('access-control-allow-methods', 'get,post,put,patch,delete,options')
            ->header('access-control-allow-headers', 'content-type');
    }
}

read this article on global middleware.


Related Query

More Query from same tag