我将Vue.js和Laravel与Axios结合使用来对我的记录进行搜索过滤。发出请求时,我的控制台中出现以下错误。
GET http://localhost:8000/api/quests/search/?keywords=test 405(方法 不允许)
Vue.js
export default {
data() {
return {
quests: [],
quest: {
id: '',
name: '',
price: '',
},
keywords: null,
}
},
watch: {
keywords(after, before) {
this.fetchSearch();
}
},
methods : {
fetchSearch() {
axios.get('/api/quests/search', { params: { keywords: this.keywords}}, {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then(res => console.log(res.data))
// data empty
.catch(error => console.log(error));
}
}
API路线
Route::get('quests/search', 'CrudsController@search');
控制器
public function search(Request $request)
{
$quests = Quest::where('name', 'like', $request->keywords)->get();
return QuestResource::collection($quests);
}
网络响应
Cache-Control: no-cache, private
Connection: close
Content-Type: application/json
Date: Mon, 03 Dec 2018 16:08:05 +0000
Date: Mon, 03 Dec 2018 16:08:05 GMT
Host: localhost:8000
X-Powered-By: PHP/7.2.10
X-RateLimit-Limit: 60
X-RateLimit-Remaining: 58
我在这里做什么错了?
答案 0 :(得分:0)
您可能缺少csrf令牌。
尝试将其添加到标题中
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
或者您也可以排除此路线,而不必将其添加到csrf中间件上的$ exclude数组中。