1

I am currently making a POST request to my laravel API using the following code...

fetch('http://laravel.dev/content', {
        method: 'POST',
        mode:'no-cors',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin':'*'
        },
        body: JSON.stringify({

        })
    })
    .then((response) => {
        console.log(response);
    });

The route looks as follows...

Route::post('/content', array('middleware' => 'cors', 'uses' => 'Test@save'));

Although I have configured cors mode, I am actually using no-cors.

My controller Test@save looks like...

class Test extends Controller
{

    public function save() 
    {
       echo "here";
    }
}

I am trying to send the string here back to the fetch request. But in my fetch request, when I do console.log(response), I get the following response...

Response {type: "opaque", url: "", status: 0, ok: false, statusText: "" ...}

Is there any way to send a custom response using my Laravel route? If so, how do I do so?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

Comments

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.

8 Comments

I set up this exact middle ware, but I still get the error message Fetch API cannot load http://laravel.dev/content. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
You have to add it to your list of middleware inside of app/Http/Kernel.php
I did. But I still get an error and I can't figure out why. I can make a repo on github if that helps, as I feel like I've tried everything to get it to work.
Well what is the error now? I have built many react apps powered by a laravel backend. I'd love to help.
this is the error message currently Fetch API cannot load http://laravel.dev/content. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.