0
votes

I'm using Vue.js and Laravel in combination with Axios to make a search filter for my records. When I make the request, I get the following error in my console.

GET http://localhost:8000/api/quests/search/?keywords=test 405 (Method Not Allowed)

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

Route::get('quests/search', 'CrudsController@search');

Controller

public function search(Request $request)
{
    $quests = Quest::where('name', 'like', $request->keywords)->get();
    return QuestResource::collection($quests); 
}

Network response

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

What am I doing wrong here?

1
Your route has {keywords} as a holder. Remove that and the preceding slash from the route, and the end slash from the URL that you're submitting to.aynber
As as note, you're going to run into issues with your search, because it's going to look for results where the name is exactly equal to your keyword search. You'll need to break it up and use the LIKE keyword search.aynber
Thanks for providing this information. I edited my question to the following and now I receive the following error: TypeError: res.json is not a function , got any tips on this?Dax
Not sure what that is, so maybe try removing it?aynber
I removed it and tried logging the data. my data object is empty but for the search 'cook' I should receive atleast one result. .then(res => console.log(res.data)), I updated my question to my code to have a better look.Dax

1 Answers

0
votes

You might be missing csrf token.

Try adding it to your header

           headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }

Or you could alternatively exclude this route vie adding it to $exclude array on csrf middleware.