php发起options请求_laravel vue options请求解决方案

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后端解决

创建中间件(如图)

6e13ff3d09c4e4308446315296caee81.png

代码:<?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)

0d22aabf6bb2536094c5fffabf7a7a78.png

这样就把所有的options请求处理了!  为啥要吧中间处理放在第一个 protected $middleware中那?由于群组路由中间件是在路由匹配过程之后才进入,因此之前实验中提及的OPTIONS请求尚未通过此处中间件的handle函数,就已经返回了,因此我们添加的中间件,需要添加到$middleware数组中,不能添加到api群组路由中间件中。

laravel vue options请求解决了  暂时先这样 追查到原因后再来详细写!

laravel vue options请求解决方案

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值