当我使用 api.php 时,Laravel8 找不到 404 错误

时间:2021-06-25 09:36:28

标签: php ajax laravel laravel-8

我正在使用 Laravel 8 制作简单的甘特图,但遇到了问题。 当我进行路由时,打开页面时出现404错误。 顺便说一下,我正在使用 xampp。 另外我是Laravel初学者,参考了某个页面的教程。 https://docs.dhtmlx.com/gantt/desktop__howtostart_php_laravel.html

[错误日志]

GET http://localhost/api/data?dhxr1624612640474=1 404 (Not Found)
(anonymous) @ ajax.js:221
e._execute @ bluebird.js:1164
D._resolveFromExecutor @ bluebird.js:3707
D @ bluebird.js:3258
_call @ ajax.js:176
query @ ajax.js:133
get @ ajax.js:137
t.load @ load.js:21
(anonymous) @ gantt:25

[查看] gantt.blade.php

<!DOCTYPE html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
 
    <script src="https://cdn.dhtmlx.com/gantt/edge/dhtmlxgantt.js"></script>
    <link href="https://cdn.dhtmlx.com/gantt/edge/dhtmlxgantt.css" rel="stylesheet">
 
    <style type="text/css">
        html, body{
            height:100%;
            padding:0px;
            margin:0px;
            overflow: hidden;
        }

    </style>
</head>
<body>
<div id="gantt_here" style='width:100%; height:100%;'></div>
<script type="text/javascript">
    gantt.config.date_format = "%Y-%m-%d %H:%i:%s";
 
    gantt.init("gantt_here");
  
    gantt.load("/api/data");
</script>
</body>

[控制器] GanttController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Task;
use App\Models\Link;

class GanttController extends Controller
{
    public function get(){
        $tasks = new Task();
        $links = new Link();
 
        return response()->json([
            "data" => $tasks->all(),
            "links" => $links->all()
        ]);
    }
}

[路线] api.php

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
    return $request->user();
});

Route::get('/data', 'GanttController@get');

我自己无法解决,但我想这是因为路由。有人可以帮我吗?

1 个答案:

答案 0 :(得分:0)

确保你的 xampp 的 apache 和 mysql 服务正在运行,并且建议以新的方式而不是旧的方式定义你的路由, 因此,首先启动您的 xampp 服务并进行更改:

Route::get('/data', 'GanttController@get');

进入

Route::get('/data', [GanttController::class, 'get']);

这是 laravel 8.x 中的新功能,然后查看您的代码,您正在创建 TaskLink 的新实例,并尝试从中获取数据,这是错误的方法.

你应该得到这样的数据:

$tasks = Task::all();
$links = Link::all();