【发布时间】: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