我已经在laravel编写了一个API系统,但是我收到了一个错误。
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.
subdomain1是我用来从subdomain2获取数据的域,subdomain2是API子域,我刚刚为此重命名了它们。
路线:
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);
}
}
这是我的Ajax中间件:
public function handle($request, Closure $next)
{
if(!$request->ajax()) {
exit('no_ajax');
}
return $next($request);
}