Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

micksp's avatar

ajax request returns null but works in postman

I am trying to make my first ajax/api request in laravel 5.3 using vue. The api call works fine in postman but gives me null from the vue request. This is my api defenition:

/**
 * Get all students with a given name
 */
public function students(Request $request) {
    $namePart = $request->namepart ? $request->namepart : '';
    // get all names like namepart
    $students = Student::where('name', 'like', '%' . $namePart . '%')->get();
    return response()->json($students);
}

and the route in routes/api.php

Route::get('/students', 'ApiController@students');

In postman I call this using my (local) url: http://admo/api/students?namepart=spe This returns an array of json objects (i removed the data values)

[
  {
    "id": 8,
    "name": "",
    "address": "",
    "zipcode": "",
    "city": "",
    "email": "",
    "date_of_birth": "",
    "permission_auto_banktransfer": "",
    "bankaccount_name": "",
    "bankaccount_number": "",
    "status": "",
    "created_at": null,
    "updated_at": null
  }
]

This is my vue code:

new Vue({
    el: '#studentlist',
    data: {
        students: []
    },
    mounted: function() {
        this.fetchStudents();
    },
    methods: {
        fetchStudents: function() {
            this.$http.get('api/students?namepart=spe', function(response) {
                this.students = response;
            })
        }
    }
});

in firebug I see the request but it returns null Does anyone see the problem here?

-- Update: if i use jQuery $.ajax instead of this.$http.get it works alright. Something with vue-resource perhaps?

0 likes
5 replies
jekinney's avatar

Check your headers. Make sure you set the headers the same as postman.

ejdelmonico's avatar
Level 53

Change to axios and either set Vue.prototype.$http=axios; or just use as documented. I find it works much better than vue resource.

micksp's avatar

Thaks for the response! @jekinney: I don't see any problems with the headers. I compared $.ajax headers with vue-resource, only difference is the handeling of X-CSRF-TOKEN which is not present in the $.ajax call (that works). There is a cookie XSRF-TOKEN in both requests however.

@ejdelmonico : might I just use jquery $.ajax or is there a reason axios is better suited for the job?

micksp's avatar

You're right, Axios works great as promissed! Though it is a little frustrating that I don't know what causes the problem with vue-resource, I'll now stick to Axios.

Please or to participate in this conversation.