Laravel无法发送请求

dbf7pr2w  于 2023-03-24  发布在  其他
关注(0)|答案(1)|浏览(102)

我在使用Laravel时遇到了一个问题,我试图从存储中获取下载链接,但是我不能,因为当我试图发送请求时,我有500个错误代码

令牌正确。
api.php

<?php

use App\Http\Controllers\AuthController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\FilesController;

Route::fallback(function () {
return abort(404);
// return view('errors.404');  // incase you want to return view
});     

Route::middleware(['auth:sanctum', 'ability:admin'])->get('/user', function (Request $request) {
if($request->user()->role == "user") return abort(403);
return response($request->user(), 200);
});

Route::get('/auth/test', [AuthController::class, 'test'])->middleware(['auth:sanctum', 'ability:admin']);

Route::post('/auth/register', [AuthController::class, 'register']);
Route::post('/auth/login', [AuthController::class, 'login']);
Route::post('/auth/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');

Route::group(['middleware' => ['auth:sanctum','ability:admin']], function() {
Route::resource('files', FilesController::class);
});

AuthController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;

class AuthController extends Controller
{
public function register(Request $request)
{
    $data = $request->validate([
        'name' => 'required|string',
        'email' => 'required|string|unique:users,email',
        'password' => 'required|string|'
    ]);

    $user = User::create([
        'name' => $data['name'],
        'email' => $data['email'],
        'password' => bcrypt($data['password']),
        'role' => 'admin'
    ]);

    $token = $user->createToken('token', [$user->role])->plainTextToken;

    $res = [
        'user' => $user,
        'token' => $token
    ];
    return response($res, 201);
}

public function login(Request $request)
{
    $data = $request->validate([
        'email' => 'required|string',
        'password' => 'required|string'
    ]);

    $user = User::where('email', $data['email'])->first();

    if (!$user || !Hash::check($data['password'], $user->password)) {
        return response([
            'message' => 'incorrect username or password'
        ], 401);
    }

    $token = $user->createToken('token', [$user->role])->plainTextToken;

    $res = [
        'user' => $user,
        'token' => $token
    ];

    return response($res, 201);
}

public function logout(Request $request)
{
    $request->user()->tokens()->delete();
    $response = ['message' => 'You have been successfully logged out!'];
    return response($response, 200);
}

public function test(Request $request)
{
    if($request->user()->role == "user") return response(['message' => 'user'], 200);
    if($request->user()->role == "admin") return response(['message' => 'admin'], 200);
}}

FilesController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\File\File;

class FilesController extends Controller
{
public function index()
{
    //
}

/**
 * Show the form for creating a new resource.
 */
public function create()
{
    //
}

/**
 * Store a newly created resource in storage.
 */
public function store(Request $request)
{

    $data = $request->validate([
        'file' => 'required|mimes:pdf|max:2048'
    ]);

    if ($file = $request->file('file')) {
        $path = $file->store('public/files');
        $name = $file->getClientOriginalName();
        $name2 = $file->hashName();

        // //store your file into directory and db
        // $save = new File();
        // $save->name = $file;
        // $save->store_path = $path;
        // $save->save();

        return response()->json([
            "success" => true,
            "message" => "File successfully uploaded",
            "file" => $file,
            "name" => $name, //oryginalna nazwa pliku
            "path" => $path, // path do pliku np. "public/files/wy8NNSV9uAvL0NPYydw5iaZDkz5XQYeFo2A7VZo0.pdf"
            "name2" => $name2 // sama nazwa pliku np. "wy8NNSV9uAvL0NPYydw5iaZDkz5XQYeFo2A7VZo0.pdf"
        ]);
    }
}

/**
 * Display the specified resource.
 */
public function show(string $filename)
{
    // tutaj powinno być id pliku i z bazy nazwa ale jako id tutaj przekazana jest nazwa pliku z storage

    $file = new File(Storage::disk('public_files')->get($filename));
    return response()->download($file->getRealPath(), $filename);
}

/**
 * Show the form for editing the specified resource.
 */
public function edit(string $id)
{
    //
}

/**
 * Update the specified resource in storage.
 */
public function update(Request $request, string $id)
{
    //
}

/**
 * Remove the specified resource from storage.
 */
public function destroy(string $id)
{
    //
}}

config/filesystems.php

'public_files' => [
        'driver' => 'local',
        'root' => storage_path('app/public/files'),
        'url' => env('APP_URL').'/storage/files',
        'visibility' => 'public',
    ],

我不知道为什么我有这个错误。方法存储工作完美,但方法显示不工作。AuthController也工作完美。
所有错误列表

<!--
Symfony\Component\Routing\Exception\RouteNotFoundException: Route             [login] not defined. in file C:\xampp\htdocs\test         Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Routing\UrlGenerator.php on line 467

#0 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\helpers.php(810): Illuminate\Routing\UrlGenerator-&gt;route(&#039;login&#039;, Array, true)
#1 C:\xampp\htdocs\test Laravel\testAuthSanctum\app\Http\Middleware\Authenticate.php(15): route(&#039;login&#039;)
#2 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php(84): App\Http\Middleware\Authenticate-&gt;redirectTo(Object(Illuminate\Http\Request))
#3 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php(69): Illuminate\Auth\Middleware\Authenticate-&gt;unauthenticated(Object(Illuminate\Http\Request), Array)
#4 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Auth\Middleware\Authenticate.php(43): Illuminate\Auth\Middleware\Authenticate-&gt;authenticate(Object(Illuminate\Http\Request), Array)
#5 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Auth\Middleware\Authenticate-&gt;handle(Object(Illuminate\Http\Request), Object(Closure), &#039;sanctum&#039;)
#6 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(116): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#7 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Routing\Router.php(799): Illuminate\Pipeline\Pipeline-&gt;then(Object(Closure))
#8 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Routing\Router.php(776): Illuminate\Routing\Router-&gt;runRouteWithinStack(Object(Illuminate\Routing\Route), Object(Illuminate\Http\Request))
#9 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Routing\Router.php(740): Illuminate\Routing\Router-&gt;runRoute(Object(Illuminate\Http\Request), Object(Illuminate\Routing\Route))
#10 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Routing\Router.php(729): Illuminate\Routing\Router-&gt;dispatchToRoute(Object(Illuminate\Http\Request))
#11 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(200): Illuminate\Routing\Router-&gt;dispatch(Object(Illuminate\Http\Request))
#12 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(141): Illuminate\Foundation\Http\Kernel-&gt;Illuminate\Foundation\Http\{closure}(Object(Illuminate\Http\Request))
#13 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#14 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull.php(31): Illuminate\Foundation\Http\Middleware\TransformsRequest-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#15 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#16 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php(21): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#17 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TrimStrings.php(40): Illuminate\Foundation\Http\Middleware\TransformsRequest-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#18 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\TrimStrings-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#19 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php(27): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#20 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\ValidatePostSize-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#21 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance.php(86): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#22 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#23 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Http\Middleware\HandleCors.php(62): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#24 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Http\Middleware\HandleCors-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#25 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Http\Middleware\TrustProxies.php(39): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#26 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(180): Illuminate\Http\Middleware\TrustProxies-&gt;handle(Object(Illuminate\Http\Request), Object(Closure))
#27 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(116): Illuminate\Pipeline\Pipeline-&gt;Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#28 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(175): Illuminate\Pipeline\Pipeline-&gt;then(Object(Closure))
#29 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(144): Illuminate\Foundation\Http\Kernel-&gt;sendRequestThroughRouter(Object(Illuminate\Http\Request))
#30 C:\xampp\htdocs\test Laravel\testAuthSanctum\public\index.php(52): Illuminate\Foundation\Http\Kernel-&gt;handle(Object(Illuminate\Http\Request))
#31 C:\xampp\htdocs\test Laravel\testAuthSanctum\vendor\laravel\framework\src\Illuminate\Foundation\resources\server.php(16): require_once(&#039;C:\\xampp\\htdocs...&#039;)
#32 {main}
-->
rt4zxlrg

rt4zxlrg1#

为什么API开发者破产了?
因为他没有包括他的第一次进攻的头球!
严重的是,当使用API时,如果请求没有将Accept头部设置为application/json,通常会发生“route login not found”错误。
错误消息中出现text/html content-type表示请求不是针对API端点,而是针对常规网页。
要通过API访问PDF文件,您可以使用值为application/pdfAccept头。这将通知服务器您希望接收具有PDF内容类型的文件作为响应。

curl -X GET \
  -H "Accept: application/pdf" \
  -H "Authorization: Bearer <access_token>" \
  http://localhost:8000/api/files/xxxx.pdf

curl -X GET \
  -H "Accept: application/octet-stream" \
  -H "Authorization: Bearer <access_token>" \
  http://localhost:8000/api/files/xxxx.pdf

值为application/pdfapplication/octet-streamAccept头的区别在于,application/pdf明确表示客户端希望接收PDF内容类型的文件作为响应,而application/octet-stream仅表示客户端希望接收二进制数据,包括未知或未指定内容类型的文件。
通过API访问PDF文件时,建议使用Accept头,其值为application/pdf,因为这明确表示客户端希望接收PDF内容类型的文件作为响应,但通过API访问PDF文件时,仍然可以使用Accept头,其值为application/octet-stream。因为客户端仍然可以接收作为二进制数据的PDF文件。

更新

问题似乎还与FilesController中的show方法有关。主要问题是您试图从文件的内容创建新的File,这是不正确的。相反,您应该获取存储文件的路径并使用它来创建Symfony\Component\HttpFoundation\BinaryFileResponse对象。

public function show(string $filename)
{
    // Get the path of the stored file
    $filePath = Storage::disk('public_files')->get($filename);

    // Check if the file exists
    if (!File::exists($filePath)) {
        return abort(404, 'File not found');
    }

    // Create a BinaryFileResponse object and return it
    return response()->file($filePath, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => 'inline; filename="' . $filename . '"'
    ]);
}

相关问题