laravel vue options请求解决方案
最近在和前端配合写vue项目时候碰到options请求,但是laravel接口规定是get就是get post就是post!
下边两种解决方案:前端引入qs#安装qs
npm install qs
#main.js中引入qs
import qs from 'qs
Vue.prototype.$qs = qs
#使用
this.$axios.post("http://xxx/",
this.$qs.stringify(postData)
).then(data => {
if (data.data.status != 200) {
//xxx
} else {
//xxx
}
});
这样就不会出现options!具体原因我还在追查~
2. laravel后端解决
创建中间件(如图)
代码:<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\URL;
class OptionsAccess
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if($request->getMethod() === 'OPTIONS'){
$origin = $request->header('ORIGIN', '*');
header("Access-Control-Allow-Origin: $origin");
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
header('Access-Control-Allow-Headers: Origin, Access-Control-Request-Headers, SERVER_NAME, Access-Control-Allow-Headers, cache-control, token, X-Requested-With, Content-Type, Accept, Connection, User-Agent, Cookie, X-XSRF-TOKEN');
}
return $next($request);
}
}
把中间件放入总中间件中(Kernel.php)
这样就把所有的options请求处理了! 为啥要吧中间处理放在第一个 protected $middleware中那?由于群组路由中间件是在路由匹配过程之后才进入,因此之前实验中提及的OPTIONS请求尚未通过此处中间件的handle函数,就已经返回了,因此我们添加的中间件,需要添加到$middleware数组中,不能添加到api群组路由中间件中。
laravel vue options请求解决了 暂时先这样 追查到原因后再来详细写!
laravel vue options请求解决方案