I have a problem in getting some data in my database. It returns HTML data.
{data: '<!DOCTYPE html>n<html lang="en">n <head>n …>n x3Cscript src="/js/app.js">x3C/script>n</html>n', status: 200, statusText: 'OK', headers: AxiosHeaders, config: {…},…}
And I am only requesting an authenticated user’s username. Here are my codes:
Vue.JS 3.0.0 Vuex
const api = axios.create({
baseURL: '/accounts',
});
async getCurrentUser(context, payload) {
try {
const response = await api.get('/accounts/get-user');
console.log(response)
context.commit('setUserLogged', response.data.current_user);
} catch (error) {
console.log(error)
}
}
Getters:
mounted(){
this.$store.dispatch('getCurrentUser')
},
computed: {
...mapGetters(['getUserLogged']),
isLogged(){
if(localStorage.getItem("auth_token")) {
return true
}
return false
},
},
My AuthController:
public function get_logged_user(){
$user_logged = auth()->user();
return response()->json(['current_user' => $user_logged, 'result' => 'Success' ]);
}
And my route:
Route::prefix('accounts')->group(function(){
Route::get('/get-user',[AuthController::class, 'get_logged_user'])->name('get_logged_user');
// other routes here...
})
I already added the bootstrap.js required codes:
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
2
Answers
You need to set content type.
According Axios’s https://github.com/axios/axios/issues/86
You need to add
data:{}
You can also solve your issue with a server-side approach. You can create a
ForceJsonMiddleware
to automatically add the required header to force your Laravel API to return JSON.Here is an example of middleware that I use in most of my projects:
Then, depending on your needs, here’s how you should register it in your
app/Http/Kernel.php
file:You want to apply it to all routes of your Laravel API ?:
You want to apply it only to certain routes ?
Create an alias :
And use it on your route file :