预检响应 vue-laravel App 中的 Access-Control-Allow-Methods 不允许方法 PUT [英] Method PUT is not allowed by Access-Control-Allow-Methods in preflight response vue-laravel App

查看:14
本文介绍了预检响应 vue-laravel App 中的 Access-Control-Allow-Methods 不允许方法 PUT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 vue 新手.对于 ajax 请求,我使用的是 axios,而对于后端,我使用的是 Laravel.每当我发送 POST 和 GET 请求时,它都可以正常工作.但是在尝试发送 PUT 请求时,它的显示方法 PUT 在预检响应 vue-laravel 应用程序中不被 Access-Control-Allow-Methods 允许.我在 Stackoverflow 和 github 中阅读了很多答案,但没有一个对我有用.

I am new in vue. For ajax request I am using axios and for back-end I am using Laravel. Whenever I send a POST and GET request it's works fine. But while trying to send a PUT Request its showing Method PUT is not allowed by Access-Control-Allow-Methods in preflight response vue-laravel App. I had read lots of answer in Stackoverflow and github but none of them worked for me.

这是客户端代码:

axios.put('http://127.0.0.1:8000/api/photo/6', this.photo, { headers: getHeader() })
    .then(response => {
        console.log(response.data.message);
   }).catch(err => {
        this.errors = err.response.data.errors;
   });

这里是CROSS中间件代码:

Here is CROSS middleware code:

//allowed client 
    //now only for localhost vue cli
    $domains = ['http://localhost:8080'];

    if(isset($request->server()['HTTP_ORIGIN'])){

        $origin = $request->server()['HTTP_ORIGIN'];

        if(in_array($origin, $domains)){
            header('Access-Control-Allow-Origin: '.$origin);
            header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
        }
    }

    return $next($request);

推荐答案

在后端试试这个:app/Http/Middleware/Cors.php

Try this in backend : app/Http/Middleware/Cors.php

public function handle($request, Closure $next)
{
return $next($request)
    ->header('Access-Control-Allow-Origin', '*')
    ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, 
OPTIONS');
}

app/Http/Kernel.php $routedMiddleware 数组添加

app/Http/Kernel.php $routedMiddleware array add

'cors' => \App\Http\Middleware\Cors::class,

路由/api.phpRoute::group(['middleware' => 'cors'], function () {

Route/api.php Route::group(['middleware' => 'cors'], function () {

Route::put('/v1/employees', 'Employees@store');

});

这篇关于预检响应 vue-laravel App 中的 Access-Control-Allow-Methods 不允许方法 PUT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆