【问题标题】:POST request is not working in REST API for Laravel 5.4POST 请求在 Laravel 5.4 的 REST API 中不起作用
【发布时间】:2017-02-13 13:17:54
【问题描述】:

我尝试使用 REST API 工具中的 post 方法发送一些值。 我使用了 Laravel 5.4 版。 我试过下面的代码

路由文件:

Route::post('ws-register',array('uses' => 'AppController@doRegister'));

控制器文件

public function doRegister() {
    $rules = array(
        'email' => 'required|email|unique:users', 
        'password' => 'required|alpha_num|min:6|max:15'
    );
    $messages = array('alpha_spaces' => 'Name must be alphanumeric');
    $validator = Validator::make(Input::all(), $rules, $messages);

    if ($validator->fails()) {
        $error = $validator->errors()->all(':message');

        $response['message'] = $error[0];
        $response['code'] = false;
    } else {
            $user = new Users;

            $user->email = Input::get('email');
            $user->password = Hash::make(Input::get('password'));
            $user->save();

            $response['user_id'] = $user->id;
            $response['message'] = "Success";
            $response['code'] = true;
        }
    }
    return Response::json($response);
}

通过 REST API POST 方法调用时,我收到“500:内部服务器错误”作为响应。 谁能帮我找出我做错了什么?

【问题讨论】:

  • 字母数字验证是​​alpha_num 不是吗?消息的格式也应为field.validationrule => message
  • @apokryfos 是的,它是一个字母数字验证
  • 是的,你有alphaNum,不应该是alpha_num吗?
  • 好的,即使我改变了验证,错误仍然是一样的。函数本身没有被调用@apokryfos
  • 在这种情况下,您应该检查错误日志(apache 日志或 laravel 日志)。

标签: php post laravel-5.4


【解决方案1】:

假设您遇到TokenMismatchException in VerifyCsrfToken.php 错误,如问题 cmets 中所写。

app/Http/Kernel.php 中所述,VerifyCsrfToken 中间件适用于routes/web.php 中的所有路由。但不适用于routes/api.php

如果您正在发出 API 请求,最好将您的路由放在 routes/api.php 文件中。然后,在进行 API 调用时,请确保在您的请求中添加 /api 前缀,如下所示:

POST http://example.app/api/ws-register

但是如果你仍然想保持你的路由在routes/web.php,考虑添加CSRF-protection。更多信息https://laravel.com/docs/5.4/csrf

【讨论】:

  • 我试过这样使用 example.com/api/ws-register ,它显示错误 302 @Petr Reshetin
  • @ArunKumar 302 是 http 重定向响应。它重定向到什么位置?您可能会在响应标头中看到它,更多信息here
  • 在响应标头中,我收到以下日期:2017 年 2 月 22 日星期三 13:00:15 GMT 服务器:Apache/2.2.29 (Unix) mod_wsgi/3.5 Python/2.7.10 PHP /7.0.8 mod_ssl/2.2.29 OpenSSL/0.9.8zh DAV/2 mod_fastcgi/2.4.6 mod_perl/2.0.9 Perl/v5.22.0 X-Powered-By: PHP/7.0.8 Cache-Control: no-cache ,私有位置:localhost:8888/website/public/login X-Ratelimit-Limit:60 X-Ratelimit-Remaining:58 Content-Length:444 Content-Type:text/html; charset=UTF-8
  • @ArunKumar 所以它重定向到登录页面,所以可能需要删除一些身份验证中间件。您可以通过php artisan route:list --path=ws-register 检查适用于您的路由的现有中间件。所以请确保您的路线不在Route::middleware('auth:api')
  • 我是 laravel 的新手。你能解释清楚一点吗@PetrReshetin
猜你喜欢
  • 1970-01-01
  • 2018-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-27
  • 2021-10-05
  • 2017-08-09
  • 2019-05-18
相关资源
最近更新 更多