如何在laravel中检查axios的请求

如何在laravel中检查axios的请求,laravel,axios,Laravel,Axios,} 我向服务器发送了axios请求。 这是服务器代码 export const category_load = ()=>{ return async (dispatch) => { await fetch('https://example.com/api/user/categorylist') .then((response) => response.json()) .then((responseJson) => { console

}

我向服务器发送了axios请求。 这是服务器代码

export const category_load = ()=>{
return async (dispatch) => {
    await fetch('https://example.com/api/user/categorylist')
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(responseJson);
    })
    .catch((error) => {
        console.error(error);
    });
}
如果我发送ajax,它将返回$Categories,但我发送axios,它将返回view。 我必须像ajax一样检查axios请求并返回$Categories。
如何解决此问题?

API端点不用于返回视图。:)使用非API端点返回视图

顺便说一句,使用当前的实现,您可以这样做:

通过Axios请求端点发送额外参数,例如,
api=true
,如下所示:

...
if($request->ajax()){
   return $Categories;
}
return view(Route::currentRouteName(), compact('Categories'));
现在,在控制器中,您可以检查
api
参数是否已设置。如果设置了,您可以像对ajax请求那样返回类别,如下所示:

export const category_load = ()=>{
return async (dispatch) => {
    await fetch('https://example.com/api/user/categorylist?api=true')
    .then((response) => response.json())
    .then((responseJson) => {
        console.log(responseJson);
    })
    .catch((error) => {
        console.error(error);
    });
}

为什么要返回API端点的视图?只需返回
$Categories而不是
返回视图(Route::currentRouteName(),compact('Categories')因为它不用于唯一的API。API端点不用于返回视图。:)使用非API端点如果我使用axios发送请求,它将返回HTML代码:(所以我认为它会返回视图。非常感谢。我解决了它,但我在您的url中使用了axios。如果我使用fetch,它会返回一个错误。
// return $Categories if the request is from Axios or Ajax
if($request->ajax() || $request->api == true) {
   return $Categories;
}
return view(Route::currentRouteName(), compact('Categories'));