Reputation: 10135
I am working on a Laravel API. My web application is making a GET
request to my API. But because the API is set to a subdomain (http://api.geladaris.dev/v1/books
), I have to use JSONP
to make Cross-Origin GET
requests work to this endpoint.
On the client side I have a polymer
element, that generates the GET
request and the server should return a jsonp
response by Laravel.
The Laravel documentation here states, that the setCallback
method is to be chained to the response like this:
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));
And that is what my index
method on my Api\BooksController
looks like:
public function index()
{
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));
}
And my Routes.php
Route::group(['domain' => 'api.geladaris.dev'], function () {
Route::group(['prefix' => 'v1'], function () {
Route::resource('books', 'Api\BooksController');
});
});
Unfortunately, all I get is a 500 Internal Server Error
, when the request is generated and the server returns above code, with the "setCallback" method:
This only happens, if I use the setCallback
Method. If I omit it, and return a normal json
response instead of jsonp
, the file is found, but I don't get the parseResponse
I get, when accessing another API, f.e. http://api.github.com/users or http://jsonplaceholder.typicode.com/posts. Notice the very first line:
I am not sure how to proceed from here on. I have disabled the CSRF
Middleware and run my routes without any Middleware.
I also tried using the api
middleware, witout any positive results.
My next aproach would be to install a CORS
library and try setting the right response headers, but I doubt that the problem will be found there, since I checked and compared the headers from three different API's (Google News, Github, Json Placeholder) to my API and the only substantial difference I found, was the missing parseResponse
before the actual returned JSON.
Therefore I wonder: How do I set the JSONP
response in Laravel to be found and not return 500 Server error?
Since the error indicates a Server Error, here some details to the server:
I am using WAMP.
My vhost
:
<VirtualHost *:80>
DocumentRoot "d:/wamp/www/geladaris/public"
ServerName geladaris.dev
ServerAlias *.geladaris.dev
</VirtualHost>
My hosts
file:
127.0.0.1 geladaris.dev
127.0.0.1 api.geladaris.dev
Upvotes: 0
Views: 11357
Reputation: 10135
Turns out that
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));
Just required the Request to be put through the index method like this:
public function index(Request $request)
{
return response()
->json(['name' => 'Abigail', 'state' => 'CA'])
->setCallback($request->input('callback'));
}
Upvotes: 1