Thursday, April 13, 2017

Larave: No 'Access-Control-Allow-Origin' header

I have coded an API system in laravel but I am receiving an error.

XMLHttpRequest cannot load http:/subdomain1.domain.com/get/call/19682a/1:0?_=1492108511546. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://subdomain2.domain.com' is therefore not allowed access.

the subdomain1 is the domain I am using to get data from subdomain2, subdomain2 is the API subdomain, I have just renamed them for this purpose.

Routes:

Route::group(['domain' => 'api.domain.com', 'namespace' => 'Api'], function() {
    Route::group(['middleware' => 'ajax'], function() {
        Route::get('/get/call/{id}/{params}', 'ApiGetController@get');
    });

    Route::get('/', function() {
        return response()->json(['response_message' => 'invalid api call']);
    });
});

ApiGetController:

<?php
namespace App\Http\Controllers\Api;

use Auth;
use App\User;
use App\Http\Controllers\Controller;
use Validator;
use Redirect;
use Illuminate\Http\Request;
use App\Database\Frontend\Other\Rooms;

class ApiGetController extends Controller
{
    public function get(Request $request, $id, $params)
    {
        $contents = response()->json(['response_message' => 'invalid api call']);
        if ($id == '19682a') {
            $paramsExploded = explode(':', $params);
            $room = Rooms::where('id', $paramsExploded[0])->first();

            if ($room != null) {
                $contents = $room->rp_locked ? 'locked' : 'unlocked';
            }
        }
        if ($id == '19682b') {
            $paramsExploded = explode(':', $params);
            $room = Rooms::where('id', $paramsExploded[0])->first();

            if ($room != null) {
                $room->rp_locked = $paramsExploded[1];
                $room->save();

                $contents = response()->json(['response_message' => 'completed']);
            }
        }

        $headers = [
            'Access-Control-Allow-Origin' => 'http://subdomain1.domain.com'
        ];

        return Response::make($contents, 200, $headers);
    }
}

Here is my Ajax middleware:

public function handle($request, Closure $next)
{
    if(!$request->ajax()) {
        exit('no_ajax');
    }

    return $next($request);
}



via VoiD HD

Advertisement