Friday, June 8, 2018

Introducing Axios, a Popular, Promise-based HTTP Client

Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js.

Making HTTP requests to fetch or save data is one of the most common tasks a client-side JavaScript application will need to do. Third-party libraries — especially jQuery — have long been a popular way to interact with the more verbose browser APIs, and abstract away any cross-browser differences.

As people move away from jQuery in favor of improved native DOM APIs, or front-end UI libraries like React and Vue.js, including it purely for its $.ajax functionality makes less sense.

Let's take a look at how to get started using Axios in your code, and see some of the features that contribute to its popularity among JavaScript developers.

Axios vs Fetch

As you’re probably aware, modern browsers ship with the newer Fetch API built in, so why not just use that? There are several differences between the two that many feel gives Axios the edge.

One such difference is in how the two libraries treat HTTP error codes. When using Fetch, if the server returns a 4xx or 5xx series error, your catch() callback won't be triggered and it is down to the developer to check the response status code to determine if the request was successful. Axios, on the other hand, will reject the request promise if one of these status codes is returned.

Another small difference, which often trips up developers new to the API, is that Fetch doesn’t automatically send cookies back to the server when making a request. It's necessary to explicitly pass an option for them to be included. Axios has your back here.

One difference that may end up being a show-stopper for some is progress updates on uploads/downloads. As Axios is built on top of the older XHR API, you’re able to register callback functions for onUploadProgress and onDownloadProgress to display the percentage complete in your app's UI. Currently, Fetch has no support for doing this.

Lastly, Axios can be used in both the browser and Node.js. This facilitates sharing JavaScript code between the browser and the back end or doing server-side rendering of your front-end apps.

Note: there are versions of the Fetch API available for Node but, in my opinion, the other features Axios provides give it the edge.

Installing

As you might expect, the most common way to install Axios is via the npm package manager:

npm i axios

and include it in your code where needed:

// ES2015 style import
import axios from 'axios';

// Node.js style require
const axios = require('axios');

If you're not using some kind of module bundler (e.g. webpack), then you can always pull in the library from a CDN in the traditional way:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Browser support

Axios works in all modern web browsers, and Internet Explorer 8+.

Making Requests

Similar to jQuery's $.ajax function, you can make any kind of HTTP request by passing an options object to Axios:

axios({
  method: 'post',
  url: '/login',
  data: {
    user: 'brunos',
    lastName: 'ilovenodejs'
  }
});

Here, we're telling Axios which HTTP method we'd like to use (e.g. GET/POST/DELETE etc.) and which URL the request should be made to.

We're also providing some data to be sent along with the request in the form of a simple JavaScript object of key/value pairs. By default, Axios will serialize this as JSON and send it as the request body.

Request Options

There are a whole bunch of additional options you can pass when making a request, but here are the most common ones:

  • baseUrl: if you specify a base URL, it'll be prepended to any relative URL you use.
  • headers: an object of key/value pairs to be sent as headers.
  • params: an object of key/value pairs that will be serialized and appended to the URL as a query string.
  • responseType: if you're expecting a response in a format other than JSON, you can set this property to arraybuffer, blob, document, text, or stream.
  • auth: passing an object with username and password fields will use these credentials for HTTP Basic auth on the request.

Convenience methods

Also like jQuery, there are shortcut methods for performing different types of request.

The get, delete, head and options methods all take two arguments: a URL, and an optional config object.

axios.get('/products/5');

The post, put, and patch methods take a data object as their second argument, and an optional config object as the third:

axios.post(
  '/products',
  { name: 'Waffle Iron', price: 21.50 },
  { options }
);

The post Introducing Axios, a Popular, Promise-based HTTP Client appeared first on SitePoint.


by Nilson Jacques via SitePoint

Set Up an OAuth2 Server Using Passport in Laravel

In this article, we’re going to explore how you could set up a fully fledged OAuth2 server in Laravel using the Laravel Passport library. We’ll go through the necessary server configurations along with a real-world example to demonstrate how you could consume OAuth2 APIs.

I assume that you’re familiar with the basic OAuth2 concepts and flow as we’re going to discuss them in the context of Laravel. In fact, the Laravel Passport library makes it pretty easy to quickly set up an OAuth2 server in your application. Thus, other third-party applications are able to consume APIs provided by your application.

In the first half of the article, we’ll install and configure the necessary libraries, and the second half goes through how to set up demo resources in your application and consume them from third-party applications.

Server Configurations

In this section, we're going to install the dependencies that are required in order to make the Passport library work with Laravel. After installation, there's quite a bit of configuration that we'll need to go through so that Laravel can detect the Passport library.

Let's go ahead and install the Passport library using composer.

That's pretty much it as far as the Passport library installation is concerned. Now let's make sure that Laravel knows about it.

Working with Laravel, you're probably aware of the concept of a service provider that allows you to configure services in your application. Thus, whenever you want to enable a new service in your Laravel application, you just need to add an associated service provider entry in the config/app.php.

If you're not aware of Laravel service providers yet, I would strongly recommend that you do yourself a favor and go through this introductory article that explains the basics of service providers in Laravel.

In our case, we just need to add the PassportServiceProvider provider to the list of service providers in config/app.php as shown in the following snippet.

Next, we need to run the migrate artisan command, which creates the necessary tables in a database for the Passport library.

To be precise, it creates following the tables in the database.

Next, we need to generate a pair of public and private keys that will be used by the Passport library for encryption. As expected, the Passport library provides an artisan command to create it easily.

That should have created keys at storage/oauth-public.key and storage/oauth-private.key. It also creates some demo client credentials that we'll get back to later.

Moving ahead, let's oauthify the existing User model class that Laravel uses for authentication. To do that, we need to add the HasApiTokens trait to the User model class. Let's do that as shown in the following snippet.

The HasApiTokens trait contains helper methods that are used to validate tokens in the request and check the scope of resources being requested in the context of the currently authenticated user.

Further, we need to register the routes provided by the Passport library with our Laravel application. These routes will be used for standard OAuth2 operations like authorization, requesting access tokens, and the like.

In the boot method of the app/Providers/AuthServiceProvider.php file, let's register the routes of the Passport library.

Last but not least, we need to change the api driver from token to passport in the config/auth.php file, as we're going to use the Passport library for the API authentication.

So far, we've done everything that's required as far as the OAuth2 server configuration is concerned.

Set Up the Demo Resources

In the previous section, we did all the hard work to set up the OAuth2 authentication server in our application. In this section, we'll set up a demo resource that could be requested over the API call.

We will try to keep things simple. Our demo resource returns the user information provided that there's a valid uid parameter present in the GET request.

Let's create a controller file app/Http/Controllers/UserController.php with the following contents.

As usual, you need to add an associated route as well, which you are supposed to add in the routes/web.php file. But what we are talking about is the API route, and thus it needs special treatment.

The API routes are defined in the routes/api.php file. So, let's go ahead and add our custom API route as shown in the following snippet.

Although we've defined it as /user/get, the effective API route is /api/user/get, and that's what you should use when you request a resource over that route. The api prefix is automatically handled by Laravel, and you don't need to worry about that!

In the next and last section, we'll discuss how you could create client credentials and consume the OAuth2 API.

How to Consume OAuth2 APIs

Now that we've set up the OAuth2 server in our application, any third party can connect to our server with OAuth and consume the APIs available in our application.

First of all, third-party applications must register with our application in order to be able to consume APIs. In other words, they are considered as client applications, and they will receive a client id and client secret upon registration.

The Passport library provides an artisan command to create client accounts without much hassle. Let's go ahead and create a demo client account.

When you run the artisan passport:client command, it asks you a few questions before creating the client account. Out of those, there's an important one that asks you the callback URL.

The callback URL is the one where users will be redirected back to the third-party end after authorization. And that's where the authorization code that is supposed to be used in exchange for the access token will be sent. We are about to create that file in a moment.

Now, we're ready to test OAuth2 APIs in the Laravel application.

For demonstration purposes, I'll create the oauth2_client directory under the document root in the first place. Ideally, these files will be located at the third-party end that wants to consume APIs in our Laravel application.

Let's create the oauth2_client/auth_redirection.php file with the following contents.

Make sure to change the client_id and redirect_uri parameters to reflect your own settings—the ones that you used while creating the demo client account.

Next, let's create the oauth2_client/callback.php file with the following contents.

Again, make sure to adjust the URLs and client credentials according to your setup in the above file.

How It Works Altogether

In this section, we'll test it altogether from the perspective of an end user. As an end user, there are two applications in front of you:

  1. The first one is the Laravel application that you already have an account with. It holds your information that you could share with other third-party applications.
  2. The second one is the demo third-party client application, auth_redirection.php and callback.php, that wants to fetch your information from the Laravel application using the OAuth API.

The flow starts from the third-party client application. Go ahead and open the http://localhost/oauth2_client/auth_redirection.php URL in your browser, and that should redirect you to the Laravel application. If you're not already logged into the Laravel application, the application will ask you to do so in the first place.

Once the user is logged in, the application displays the authorization page.

If the user authorizes that request, the user will be redirected back to the third-party client application at http://localhost/oauth2_client/callback.php along with the code as the GET parameter that contains the authorization code.

Once the third-party application receives the authorization code, it could exchange that code with the Laravel application to get the access token. And that's exactly what it has done in the following snippet of the oauth2_client/callback.php file.

Next, the third-party application checks the response of the CURL request to see if it contains a valid access token in the first place.

As soon as the third-party application gets the access token, it could use that token to make further API calls to request resources as needed from the Laravel application. Of course, the access token needs to be passed in every request that's requesting resources from the Laravel application.

We've tried to mimic the use-case in that the third-party application wants to access the user information from the Laravel application. And we've already built an API endpoint, http://your-laravel-site-url/api/user/get, in the Laravel application that facilitates it.

So that's the complete flow of how you're supposed to consume the OAuth2 APIs in Laravel.

And with that, we’ve reached the end of this article.

Conclusion

Today, we explored the Passport library in Laravel, which allows us to set up an OAuth2 server in an application very easily. 

For those of you who are either just getting started with Laravel or looking to expand your knowledge, site, or application with extensions, we have a variety of things you can study in Envato Market.

Don't hesitate to share your thoughts and queries using the feed below!


by Sajal Soni via Envato Tuts+ Code

Priority Nav Scroller with JavaScript

Priority Nav Scroller is a plugin for the priority+ navigation pattern. When the navigation items don’t fit on screen they are hidden in a horizontal scrollable container with controls.

The post Priority Nav Scroller with JavaScript appeared first on Best jQuery.


by Admin via Best jQuery

Facebook launches gaming video hub in attempt to rival Twitch

Facebook is going after those eyeballs on Twitch. The social network has launched fb.gg, a hub which makes it easier for people to find gaming content that's been streamed on the platform. Front and centre in the hub are primarily popular titles such as Fortnite, PUBG and FIFA 18, as well as...

[ This is a content summary only. Visit our website https://ift.tt/1b4YgHQ for full links, other content, and more! ]

by Web Desk via Digital Information World

Fun: How to Love the Work You Do

Are you struggling to balance your work and personal life? Wondering if the hustle and grind are worth the toll they take on you? To explore how to bring fun back into your work, I interview Joel Comm. More About This Show The Social Media Marketing podcast is an on-demand talk radio show from Social Media [...]

The post Fun: How to Love the Work You Do appeared first on .


by Michael Stelzner via

Navigation Menu Style 40

The post Navigation Menu Style 40 appeared first on Best jQuery.


by Admin via Best jQuery

Link Hover Style 23

The post Link Hover Style 23 appeared first on Best jQuery.


by Admin via Best jQuery