Laravel 5.7上的ajax post返回405(不允许的方法)

时间:2018-10-30 14:28:10

标签: ajax laravel

您好:)我有一个注册表,并将Ajax发布数据发送到控制器,但控制台返回 405 错误。下面是我的代码:

JavaScript代码:

// you can also use imports, for example:
// import java.util.*;

// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {

    /**
     * The solution is quite simple instead of passing through double loops
     * you only increment your counter when you meet a car going West
     * and you increment by number of cars going East that you've seen so far.
     */
    public int solution(int[] A) {

        int numCarsGoingEast = 0;
        int numPassing = 0;

        if (A.length > 1) {

            for (int i = 0; i < A.length; i++) {

                if (A[i] == 0) {

                    numCarsGoingEast++;
                } else {

                    numPassing += numCarsGoingEast;
                }

                if (numPassing > 1000000000) return -1;
            }
        }

        return numPassing;
    }
}

路线 $(function () { $('.btn-register').click(function (e) { e.preventDefault(); var post = $('#register_form').serialize(); console.log(post); $.ajax({ type : 'post', url :'/user/register/', data : post, success : function (data) { console.log(data); } }); }) })

web.php

我的注册表:

## User Section ##
Route::group(['prefix'=>'user'],function (){

    Route::post('register',function (\Illuminate\Http\Request $request){
        return $request;
    });

    # User MiddleWare
    Route::group(['middleware'=>'user'],function (){

    });
});

发布更新并添加注册表。我正常测试了此表单,并且在没有Ajax的情况下也很好,并且没有问题。但是当我使用<form method="post" action="/user/register" id="register_form"> <div class="form-group text-right"> <div class="input-group"> <input type="text" class="form-control text-left" name="email"> </div> </div> <div class="form-group text-right"> <div class="input-group"> <input type="text" class="form-control text-right" name="name"> </div> </div> <div class="form-group text-right"> <div class="input-group"> <input type="password" class="form-control text-left" name="password"> </div> </div> <div class="form-group"> <input type="submit" class="btn btn-primary btn-register" value="reg"> </div> </form> $.ajax时会返回错误!!!

2 个答案:

答案 0 :(得分:1)

感谢@simonecosci。更改Ajax网址工作:

url :'/user/register/'

url :'/user/register'

答案 1 :(得分:0)

在您的JavaScript代码中发现错误

$(function () {
    $('.btn-register').click(function (e) {
        e.preventDefault();
        var post = $('#register_form').serialize();
        console.log(post);
        $.ajax({
            type : 'post',
                url :'/user/register',
            data : post,
            success : function (data) {
                console.log(data);
            },
            error: function (error) {//add this also so you can get error if uccers
                 console.log(error);
            }
        });
    })
});