Small white side learn to write, a Laravel-based app interface "API" (ii)

Source: Internet
Author: User
Tags what callback


According to the previous article, we have DINGO/API to install and debug, then the next step is to improve our API.

The most important step must be the registration of the function to perfect, well, then give the first official API name it--


First, this API is analyzed. This is a user registration of the API, the new user by accessing it to register the account, before they have permission to do other operations, enjoy the other app services. So when we visit, we should input the correct information, because the client is the app, so the fields to be entered should be these-(mobile phone number) phone, (password) password.

So after everything is ready, what callback do we get when the server finishes processing?

Next is my own as a novice small white personal understanding. Once the registration is successful, we should immediately return the token value that confirms the user's login and store it as the config variable for the app until it is deleted on exit or after the time is exceeded.

Finish the analysis and start practicing

Before we get started, we're going to install JWT (JSON WEB TOKEN) in the project, which is a way of validating the API, and the detailed part is going to look at the document, and its main function is to return a TOKEN value after the client's user has issued a registration and login request. After a successful login, the token value is used as the credential to verify the permission to obtain the resource.

How to install please see this JWT

Once you've set up your JWT, you'll start by creating a route.

First open the routes.php, modify the route

Route::p ost ('/register ', ' auth\authenticatecontroller@register ');

Then create a controller that runs under the Laravel project

PHP Artisan Make:controller Auth/authenticatecontroller

Next, we use pure HTML page as the app, go to test the API, create a new test folder, the structure is as follows

test/├──css/│   └──bootstrap.min.css├──js/│   ├──jquery.min.js│   └──bootstrap.min.js├──fonts/│   ├── glyphicons-halflings-regular.eot│   ├──glyphicons-halflings-regular.svg│   ├── glyphicons-halflings-regular.ttf│   ├──glyphicons-halflings-regular.woff│   └── Glyphicons-halflings-regular.woff2└──register.html

Add content to the register.html file

   Toggle  navigation                                                                                                                                          
  I ·APP
    • Login

Add the following function to the Authenticatecontroller

 Only (' email ', ' password '); try {//attempt to verify the credentials and create a tokens for the user if (! $token = jwtauth::a            Ttempt ($credentials)) {return response ()->json ([' error ' = ' = ' invalid_credentials '], 401);            }} catch (Jwtexception $e) {//something went wrong whilst attempting to encode the token        return response ()->json ([' Error ' = ' Could_not_create_token '], 500);    }//All good so return the token return response ()->json (Compact (' token '));            The Public Function register (Request $request) {$newUser = [' name ' = + $request->get (' name '),        ' Phone ' = $request->get (' phone '), ' password ' + bcrypt ($request->get (' password ')),        ];        $user = User::create ($newUser);        $token = Jwtauth::fromuser ($user);    return response ()->json (Compact (' token ')); }}

The simple example is to store the requested data and return the token value.

I'm going to have to talk about a big hole I met.

In fact, according to the above code can completely write a new user to the database. But!

Token value cannot be returned! This makes people very big. So I looked at the article and found that the above operations are called cross-domain requests. Also mentioned in the Laravel documentation, yes, that's what called JSONP. So I read some articles and modified the Ajax method to look like this.

$.ajax ({    type: "Get",    URL: "Http://localhost/register",    Data: $ (this). Serialize (),    Async:false,    dataType: ' Jsonp ',    jsonp: ' Callback '    success:function (data) {        alert (json.stringify (data));     } ,    complete:function () {        alert (' OK ');    },    error:function (XMLHttpRequest, Textstatus, Errorthrown ) {        alert (xmlhttprequest.status);        alert (xmlhttprequest.readystate);        alert (textstatus);    }});

This can be written in again, but! There is no token value to appear ...

Also, the request was replaced by get, which is why? Later I know this is because Jsonp and post is impossible to achieve, or it is too difficult to realize, so I will not embarrass myself. I was completely off the run ... And the method of the Ajax to change back, open the console, and then try again, only to find that the original want to achieve cross-domain, in the header of the request to add the Access-control-allow-origin attribute.

This feels hopeful, so create an HTTP middleware right away.

PHP Artisan Make:middleware Accessmiddleware

Write it in there.


Remember to register the middleware in the kernel.php file, add it in the $routeMiddleware

' Access ' = \app\http\middleware\accessmiddleware::class,

Next, we'll modify the route.

Route::group ([' middleware ' = ' access '], function () {    Route::p ost ('/register ', ' auth\ Authenticatecontroller@register ');});

Then test it, enter the form, click Register Now, then the Bingo,token value comes out.

User information is also written normally, and then you can happily expand the registration mechanism.

Let's start with a plan here. Form validation is added to the controller first, and then different JSON data is returned to the client. But after all, I am not a professional, I just love this to write these things, about what data should be returned now the brain is still a mess. If there is a great God accidentally saw my this article, hope can give me a little guidance and advice, very grateful!

At last

The above example is entirely my own view of the document + original to the whole out, if wrong please tell me in time yo ~

The above example to the last although all achieved, but I still feel very low, after all, personal wisdom is limited. If you have a very interested in this, you can contact me, we can learn while doing, and common progress! My e-mail:

If the great God passing by, please be sure to give me some guidance, small white will be extremely grateful O (∩_∩) o~~

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.