带补丁请求laravel的HttpNotFoundException

时间:2016-12-09 12:03:01

标签: jquery ajax laravel

我是Laravel的新人。当我使用Postman向Controller发出补丁请求时一切正常,但是当我尝试使用jQuery ajax时,它会抛出一个错误:

  

供应商\ laravel \ framework \ src \ Illuminate \ Routing \ RouteCollection.php#161

中的HttpNotFoundException

我的路线:

Route::group(['prefix' => 'home'], function () {
    Route::patch('products/{id}','ProductController@update')->middleware('auth');
});

我的控制器:

public function update(Request $request, $id)
{
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:60',
        'id_category' => 'required|not_in:select',
        'quantity' => 'required|numeric',
        'purchase_price' => 'required|numeric',
        'sale_price' => 'required|numeric',
        'warning_level' => 'required|numeric',
        'alert_level' => 'required|numeric',
        'fpoints_togive' => 'numeric',
        'fpoints_cost' => 'numeric',
        'iva' => 'in:4,10,21'
    ]);
    if ($validator->fails ())
        return Response::json ( array (
            'errors' => $validator->getMessageBag()->toArray ()
        ) );
    else {
        try {
            DB::beginTransaction();

            //$id_shop = Shop_users::where('id_user', Auth::user()['attributes']['id']);
            $id_shop = DB::select('select id_shop from shop_users where id_user = '.Auth::user()['attributes']['id'])[0]->id_shop;

            $shop_pr = DB::table('shop_products')
                ->where('id_shop', $id_shop)
                ->where('id_product', $id)
                ->select('quantity', 'purchase_price', 'sale_price', 'active', 'warning_level', 'alert_level', 'fpoints_togive', 'fpoints_cost');

            if($request->active == 'on')  $active = 1; else $active = 0;

            DB::table('shop_products')
                ->where('id_product', $id)
                ->update(
                    ['quantity' => $request->quantity],
                    ['purchase_price' => $request->purchase_price],
                    ['sale_price' => $request->sale_price],
                    ['active' => $active],
                    ['warning_level' => $request->warning_level],
                    ['alert_level' => $request->alert_level],
                    ['fpoints_togive' => $request->fpoints_togive],
                    ['fpoints_cost' => $request->fpoints_cost]
                );

            $shop_pr = DB::table('shop_products')
                ->where('id_product', $id)
                ->get();
            //dd($shop_pr);

            DB::table('products')
                ->where('id', $id)
                ->update(
                    ['name' => $request->name],
                    ['id_category' => $request->id_category],
                    ['iva' => $request->iva]
                );

            $product = DB::table('products')
                ->where('id', $id)
                ->get();

            DB::commit();

            $category = DB::select('select name from categories where id = '.$request->id_category)[0]->name;

            return response ()->json ([
                'product' => $product,
                'shop_pr' => $shop_pr,
                'category' => $category
            ]);

        } catch(Exception $e) {
            DB::rollBack();
            return Response::json ( array (
                'errors' => array(
                    'name' => 'Server error'
                )
            ) );
        }

    }
}

我的观点:

$('#updbtn').click(function (){
    $.ajax({
        type: 'patch',
        url: '/home/products'+$('input[name=updid]').val(),
        headers: {
            'Content-Type':'application/x-www-form-urlencoded',
        },
        data: {
            '_token': '{!! csrf_token() !!}',
            'quantity': $('input[name=updquantity]').val(),
            'purchase_price': $('input[name=updprecio_compra]').val(),
            'sale_price': $('input[name=updprecio_venta]').val(),
            'active': $('input[name=updactive]').val(),
            'warning_level': $('input[name=updnivel_aviso]').val(),
            'alert_level': $('input[name=updnivel_alerta]').val(),
            'fpoints_togive': $('input[name=updpuntos_entregados]').val(),
            'fpoints_cost': $('input[name=updcoste_fidelidad]').val(),
            'name': $('input[name=updp_name]').val(),
            'iva': $('select[name=updiva] option:selected').val(),
            'id_category': $('select[name=updcategory] option:selected').val()
        },
        success: function(data) {
            if ((data.errors)) {
                $.notify({
                    icon: 'fa fa-exclamation-triangle',
                    message: data.errors.name
                },{
                    type: 'danger'
                });
            } else {
                $.notify({
                    icon: 'fa fa-check',
                    message: 'Producto modificado correctamente'
                },{
                    type: 'success'
                });
                //var faactive;
                //if(data.shop_pr.active == 1) {faactive = '<i class="fa fa-check"></i>'; } else { faactive = '<i class="fa fa-times"></i>' };
                //$('#dataTable tr:last').after('<tr id="cat'+data.product.id+'"><td>'+data.product.id+'</td><td>'+data.product.name+'</td><td>'+data.product.category+'</td><td>'+data.shop_pr.quantity+'</td><td>'+data.shop_pr.purchase_price+'€</td><td>'+data.product.iva+'%</td><td>'+data.shop_pr.sale_price+'€</td><td>'+data.shop_pr.warning_level+'</td><td>'+data.shop_pr.alert_level+'</td><td>'+data.shop_pr.fpoints_togive+'</td><td>'+data.shop_pr.fpoints_cost+'</td><td>'+data.shop_pr.updated_at+'</td><td>'+faactive+'</td><td><a data-toggle="modal" data-original-title="Modificar" href="#modifyModal" onclick="fillupdModal(&#39;'+data.id+'&#39;, &#39;'+data.name+'&#39;, &#39;'+data.updated_at+'&#39;)" class="btn btn-warning">Modificar</a></td><td><a data-toggle="modal" data-original-title="Eliminar" href="#deleteModal" onclick="filldelModal(&#39;'+data.id+'&#39;, &#39;'+data.name+'&#39;)" class="btn btn-danger">Eliminar</a></td></tr>');
            }

        },
        error: function(data) {
            $.notify({
                icon: 'fa fa-times',
                message: 'Error interno del servidor, por favor inténtelo de nuevo más tarde'
            },{
                type: 'danger'
            });
        },
    });
});

我尝试了很多东西,但我不知道如何解决这个错误。

1 个答案:

答案 0 :(得分:1)

如果您在浏览器控制台中查看“网络”标签,则可以看到$.ajax向错误的url发送了请求,并且因为您正在添加{{1} 1}} in:

/home

应该只是:

url: '/home/products'+$('input[name=updid]').val(),

希望这有帮助。