【问题标题】:AJAX 404 error on Laravel 5.5 artisan serverLaravel 5.5 工匠服务器上的 AJAX 404 错误
【发布时间】:2019-07-27 22:24:00
【问题描述】:

我在 Bitnami WAMP 堆栈上使用 Laravel 5.5、PHP 7,当我通过 GET 向命中控制器方法的路由发送 AJAX 请求时收到 404 错误。

这里是 web.php:

Route::get('/', 'HomeController@index'); //works
Route::get('/loadstores/{$city}', 'HomeController@show'); //404
Route::view('/aboutus', 'aboutus'); //works

HomeController.php:

public function show($city) //never gets here
{
    $stores = DB::table('stores')->where('city', $city);
    return response()->json([
        'success' => "ok"
    ]);

}

googlemaps.js:

function getIP(){
    $.getJSON('http://ip-api.com/json/', function(result) {
        console.log(result);
        userIPlocation = {lat: result.lat, lng: result.lon};
        userCity = result.city;
        getStoresByCity();
    });
}


function getStoresByCity(){
    userCity = "new york"; //test
    $.ajax({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        method:'GET',
        url:'/loadstores',
        data:{city:userCity},
        dataType: 'JSON',
        done:function(data){
            console.log("hi"); //never gets here
            console.log(data);
        },
        fail:function(xhr,status,error){
            console.log("fail"); //never gets here
            console.log(xhr,status,error);
        }
    });
}

这是 Chrome 控制台中的消息:http://localhost:8000/loadstores?city=new%20york 404 (Not Found) GET

我设置了 csrf 令牌,但我认为它甚至不需要,因为这是一个 GET 请求。

值得注意的是,我使用的是 PHP artisan serve,因此 Apache 不会参与其中,因为这是我的 .htcaccess,我永远不会被重定向到 google

.htcacess:

<IfModule mod_rewrite.c>
    Redirect 301 / https://google.com
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    Options +FollowSymLinks
    RewriteEngine On
    RewriteBase /

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

这是 php artisan route:list:

    +--------+----------+--------------------+------+-------------------------------------------+--------------+
    | Domain | Method   | URI                | Name | Action                                    | Middleware   |
    +--------+----------+--------------------+------+-------------------------------------------+--------------+
    |        | GET|HEAD | /                  |      | App\Http\Controllers\HomeController@index | web          |
    |        | GET|HEAD | api/user           |      | Closure                                   | api,auth:api |
    |        | GET|HEAD | loadStores/{$city} |      | App\Http\Controllers\HomeController@show  | web          |
|        | GET|HEAD | aboutus            |      | \Illuminate\Routing\ViewController        | web          |

我已经多次清除路由缓存。如果我删除发送到 /loadstores 的参数以及 show() 中的 $city,我会在页面上收到 JSON 成功消息。

这里很困惑,谢谢!

【问题讨论】:

    标签: javascript php jquery ajax laravel


    【解决方案1】:

    进行以下更改:

    在你的 routes/web.php 中:

    Route::get('/loadstores/{city}', 'HomeController@show'); 
    

    在您的 HomeController 中:

    public function show(Request $request,$city) 
    {
        $stores = DB::table('stores')->where('city', $city)->get();
        return response()->json([
            'success' => "ok",
            'stores'=>$stores
        ]);
    }
    

    在 googlemaps.js 中:

    function getIP(){
        $.getJSON('http://ip-api.com/json/', function(result) {
            console.log(result);
            userIPlocation = {lat: result.lat, lng: result.lon};
            userCity = result.city;
            getStoresByCity(userCity);
        });
    }
    
    
    function getStoresByCity(userCity){
    
        $.ajax({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            method:'GET',
            url:`/loadstores/${userCity}`,
            dataType: 'JSON',
            success:function(data){
                console.log(data);
            },
            error:function(xhr,status,error){
                console.log(xhr,status,error);
            }
        });
    }
    

    【讨论】:

      【解决方案2】:

      您的路由Route::get('/loadstores/{city}', 'HomeController@show'); 意味着它将路由绑定到遵循/loadstores/new-york 模式的url,并将new-york 绑定到控制器中的变量$city。

      首先要注意的是,路由定义中的$ 在那里不需要,应该将其删除,将路由更改为:Route::get('/loadstores/{city}', 'HomeController@show')。

      第二件事是你现在尝试绑定一个 GET 参数,而你的路由需要一个查询参数。如果您将网址更改为loadstores/new-york,它应该可以工作。或者,如果您想使用 GET 参数,请将其更改为 Route::get('/loadstores, "HomeController@show");`

      【讨论】:

      • 这是最有帮助的回复。它帮助我了解问题的根本原因并向我展示了解决方案。其他答案都很好,但这个回答是最准确的。
      猜你喜欢
      • 2018-04-01
      • 1970-01-01
      • 2016-08-17
      • 2021-05-22
      • 2016-08-31
      • 2018-10-29
      • 2018-05-07
      • 2018-06-03
      • 2021-08-17
      相关资源
      最近更新 更多