首页 > 解决方案 > GET 请求返回发送页面的 HTML

问题描述

我正在使用 Nuxt/Vue 和 Laravel 制作网站,前端工作正常,通过后端我能够连接到数据库、迁移表、种子数据等。

问题是当我在我的主 Vue 文件中使用 Axios GET 请求时,返回的只是:

data: "<!doctype html>↵&lt;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>↵&lt;/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

我假设这与我的 Laravel 路由/控制器/模型/资源有关,但我对此很陌生,完全不知道。

Axios 请求:

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

api.php 中的路由:

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

物品控制器:

<?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));
    }
}

商品型号:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

项目资源:

<?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,
        ];
    }
}

如果有任何用处,这里是入门模板:

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

任何帮助,即使只是为我指明正确的方向,都会让我头疼。

如果我没有发布任何有用的东西,请告诉我。

标签: javascriptphplaravelvue.jsnuxt.js

解决方案


在 laravel 中,您需要添加Accept: applicaion/json标头才能获得JSON响应。否则它将返回HTML response

Accept标题添加到您的Axios Request.

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

注意: 如果您没有api在中添加前缀nuxt.config.js,则需要在 url 中添加它,例如api/items


推荐阅读