简体   繁体   English

POST请求在Laravel 5.4的REST API中不起作用

[英]POST request is not working in REST API for Laravel 5.4

I have tried to send some values using post method in REST API Tool. 我尝试使用REST API工具中的post方法发送一些值。 I have used Laravel version 5.4. 我使用过Laravel 5.4版。 I have tried the following code 我尝试了以下代码

Route File: 路由文件:

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

Controller File 控制器文件

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

While calling through REST API POST Method, I am getting "500: Internal Server Error" as response. 通过REST API POST方法调用时,我得到“ 500:内部服务器错误”作为响应。 Can anyone help me out to find what I have done wrong? 谁能帮我找出我做错了什么?

Assuming you are having TokenMismatchException in VerifyCsrfToken.php error, as was written in question comments. 假设您TokenMismatchException in VerifyCsrfToken.php错误TokenMismatchException in VerifyCsrfToken.php ,如问题注释中所写。

As stated in app/Http/Kernel.php , VerifyCsrfToken middleware is applied to all routes in routes/web.php . app/Http/Kernel.php ,VerifyCsrfToken中间件将应用于routes/web.php所有路由。 But it is not applied to routes/api.php 但是它不适用于routes/api.php

If you are making API request, may be it is better to place your route in routes/api.php file. 如果您要发出API请求,可能最好将路由放置在routes/api.php文件中。 Then, when making API call, make sure to add /api prefix to your request, like this: 然后,在进行API调用时,请确保在请求中添加/api前缀,如下所示:

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

But if you still want to to keep your route in routes/web.php , think of adding CSRF-protection. 但是,如果您仍然希望将路由保留在routes/web.php ,请考虑添加CSRF保护。 More info at https://laravel.com/docs/5.4/csrf 更多信息请参见https://laravel.com/docs/5.4/csrf

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM