【问题标题】:Not returning JSON reponse in Laravel在 Laravel 中不返回 JSON 响应
【发布时间】:2018-09-10 14:25:51
【问题描述】:

我为 API 创建了一个逻辑,在该逻辑中我使用了一个函数来检查请求是否为 POST。如果不是,它应该返回一个错误。

AuthController.php 看起来像这样:

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;

class AuthController extends Controller {
private static function allowOneMethod($request, $allowed_method, $success_function){
    $method = $request->method();
    if ($method != $allowed_method){
        return response()->json(['status' => 'error', 'message' => 'Method not Allowed.'], 405);
    } else{
        $success_function();
    }
}

public function register(Request $request)
{

    $this->allowOneMethod($request, 'POST', function() {
        return response()->json(['status' => 'success', 'message' => 'It is a POST request.'], 200);
    });

}
...

routes/api.php 看起来像这样:

Route::any('/register', 'AuthController@register');

但我看到的只是一个空白的回复。 可能是什么原因?

【问题讨论】:

  • 你没有从寄存器返回任何东西。
  • 但是我需要返回什么???我需要返回的所有内容都已启动..
  • 为什么不在路由文件本身中路由发布请求?
  • 您遇到了一些问题。在闭包中返回不会从寄存器返回任何内容。
  • 是的。我尝试返回一些响应。即使是获取请求它也会返回它

标签: php laravel rest api request


【解决方案1】:

你没有返回你的 allowOneMethod() 方法

public function register(Request $request)
{
// you need to return your method value 
    return $this->allowOneMethod($request, 'POST', function() {
        return response()->json(['status' => 'success', 'message' => 'It is a POST request.'], 200);
    });

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-25
    • 1970-01-01
    • 2020-10-11
    • 2015-01-26
    • 2020-02-20
    • 2016-12-07
    • 2021-01-24
    • 2017-04-19
    相关资源
    最近更新 更多