写好了api,手机端来调用的时候,可以操作数据库,但是接收不到后端的返回值。出现了这样的情况,如果代码没有错误,那就应该是跨域的问题了。
写个中间件AllowAcross.php:
<?php
namespace App\Http\Middleware;
use Closure;
class AllowAcross
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE, PATCH',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, OriginOrigin, Cookie, Accept, multipart/form-data, application/json',
'Access-Control-Allow-Credentials' => 'false',
];
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
然后在kernel.php文件中配置中间件:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
//这就是所加的中间件
'allow' => \App\Http\Middleware\AllowAcross::class,
];
然后在routes.php中配置好路由
Route::group(['middleware'=>['allow'],'prefix'=>'api','namespace'=>'Api'],function(){
//校对版本信息
Route::post('version', 'IndexController@version');
}
这样跨域问题就解决了!