1
votes

I'm using Nuxt/Vue and Laravel to make a website, the frontend works fine and with the backend I'm able to connect to the database, migrate tables, seed data etc.

The problem is when I use an Axios GET request in my main Vue file, all that's returned is this:

data: "<!doctype html>↵<html data-n-head="">↵  <head data-n-head="">↵    <title data-n-head="true">B&amp;B Vintage Collectibles - B&amp;B Vintage Collectibles</title><meta data-n-head="true" charset="utf-8"><meta data-n-head="true" name="viewport" content="width=device-width, initial-scale=1"><meta data-n-head="true" data-hid="description" name="description" content="B&amp;B Vintage Collectibles"><link data-n-head="true" rel="icon" type="image/x-icon" href="/favicon.ico"><link data-n-head="true" rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"><link rel="preload" href="/_nuxt/runtime.js" as="script"><link rel="preload" href="/_nuxt/commons.app.js" as="script"><link rel="preload" href="/_nuxt/vendors.app.js" as="script"><link rel="preload" href="/_nuxt/app.css" as="style"><link rel="preload" href="/_nuxt/app.js" as="script">↵  <link href="/_nuxt/app.css" rel="stylesheet"></head>↵  <body data-n-head="">↵    <div id="__nuxt"><style>#nuxt-loading {  visibility: hidden;  opacity: 0;  position: absolute;  left: 0;  right: 0;  top: 0;  bottom: 0;  display: flex;  justify-content: center;  align-items: center;  flex-direction: column;  animation: nuxtLoadingIn 10s ease;  -webkit-animation: nuxtLoadingIn 10s ease;  animation-fill-mode: forwards;  overflow: hidden;}@keyframes nuxtLoadingIn {  0% {visibility: hidden;opacity: 0;  }  20% {visibility: visible;opacity: 0;  }  100% {visibility: visible;opacity: 1;  }}@-webkit-keyframes nuxtLoadingIn {  0% {visibility: hidden;opacity: 0;  }  20% {visibility: visible;opacity: 0;  }  100% {visibility: visible;opacity: 1;  }}#nuxt-loading>div,#nuxt-loading>div:after {  border-radius: 50%;  width: 5rem;  height: 5rem;}#nuxt-loading>div {  font-size: 10px;  position: relative;  text-indent: -9999em;  border: .5rem solid #F5F5F5;  border-left: .5rem solid #007bff;  -webkit-transform: translateZ(0);  -ms-transform: translateZ(0);  transform: translateZ(0);  -webkit-animation: nuxtLoading 1.1s infinite linear;  animation: nuxtLoading 1.1s infinite linear;}#nuxt-loading.error>div {  border-left: .5rem solid #ff4500;  animation-duration: 5s;}@-webkit-keyframes nuxtLoading {  0% {-webkit-transform: rotate(0deg);transform: rotate(0deg);  }  100% {-webkit-transform: rotate(360deg);transform: rotate(360deg);  }}@keyframes nuxtLoading {  0% {-webkit-transform: rotate(0deg);transform: rotate(0deg);  }  100% {-webkit-transform: rotate(360deg);transform: rotate(360deg);  }}</style><script>window.addEventListener('error', function () {  var e = document.getElementById('nuxt-loading');  if (e) e.className += ' error';});</script><div id="nuxt-loading" aria-live="polite" role="status"><div>Loading...</div></div><!-- https://projects.lukehaas.me/css-loaders --></div>↵  <script type="text/javascript" src="/_nuxt/runtime.js"></script><script type="text/javascript" src="/_nuxt/commons.app.js"></script><script type="text/javascript" src="/_nuxt/vendors.app.js"></script><script type="text/javascript" src="/_nuxt/app.js"></script></body>↵</html>↵"
status: 200
statusText: "OK"
headers: {accept-ranges: "none", connection: "keep-alive", content-length: "3053", content-type: "text/html; charset=utf-8", date: "Mon, 06 Apr 2020 10:07:21 GMT", …}
config: {url: "/api/items", method: "get", headers: {…}, baseURL: "http://localhost:3000/", transformRequest: Array(1), …}
request: XMLHttpRequest {readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, onreadystatechange: ƒ, …}
__proto__: Object

I'm assuming it's something to do with my Laravel route/controller/model/resource but I'm very new to this and have absolutely no idea.

Axios request:

  created() {
    const { data } = this.$axios
      .get("/items")
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  },

Route in api.php:

Route::get('/items', 'ItemsController@index');

ItemsController:

<?php

namespace App\Http\Controllers;

use App\Http\Resources\ItemResource;
use App\Item;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Faker\Generator;

class ItemsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return ItemResource::collection(Item::paginate(10));
    }
}

Item model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    public function item() {
        return Item::all();
    }
}

ItemResource:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class ItemResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'name' => $this->name,
            'description' => $this->description,
        ];
    }
}

Here's the starter template if it's of any use:

https://github.com/cretueusebiu/laravel-nuxt

Any help, even just pointing me in the right direction, would really save me a headache.

If there's anything useful I haven't posted, let me know.

1
All api routes are prefixed with api. So in your get request .get('api/items'). - Dino Numić
@DinoNumić I tried that but it's already prepended with 'api' from the nuxt.config.js file so it doesn't make a difference - Daniel_Knights

1 Answers

0
votes

In laravel, You need to add Accept: applicaion/json header to get JSON response. Otherwise it will return HTML response.

Add Accept Header to your Axios Request.

created() {
    const { data } = this.$axios
      .get("/items",{headers: {"Accept":"application/json"}})
      .then((res) => {
        console.log(res);
      })
      .catch((err) => {
        console.log(err);
      });
  },

NOTE : If you haven't add prefix api in nuxt.config.js, you need to add it in url like api/items