前端使用api连接后端的吗_在前端使用API

本文探讨了前端如何利用API与后端进行通信。在现代Web开发中,前端应用通常通过API调用来获取和发送数据到后端服务器。
摘要由CSDN通过智能技术生成

前端使用api连接后端的吗

As a Web Developer there is so much stuff to learn and if you’re anything like me, sometimes you get lost in the sea of things you “need to know”.

作为Web开发人员,有很多东西要学习,而且如果您像我一样,有时会迷失在“需要知道”的事物中。

But out of all those things you need to learn, there is one thing that will spice up your applications and make you look like an expert developer to potential employers.

但是,在您需要学习的所有内容中,有一件事可以使您的应用程序更加有趣,并使您看起来像潜在雇主的专家开发人员。

That one thing is how to use an API.

一件事就是如何使用API​​。

Using an API allows you to make any website or web application more exciting and dynamic than what you can accomplish with html,css and javascript by themselves. So in this post, I am going to help you learn more about APIs and how you can use them through a simple project.

与使用html,css和javascript本身可以实现的功能相比,使用API​​可以使任何网站或Web应用程序更加令人兴奋和动态。 因此,在本文中,我将帮助您了解有关API的更多信息以及如何通过一个简单的项目使用它们。

In this project we will be making use of the Unsplash API to create an image gallery. Throughout the post, I will be providing commented code snippets as well as an explanation of what the code is doing at each point.

在这个项目中,我们将使用Unsplash API创建图片库。 在整个帖子中,我将提供注释的代码段以及每点代码的作用说明。

那么什么是API? (So what is an API?)

API is an acronym that stands for Application Programming Interface and according to wikipedia, an application programming interface (API) is a computing interface which defines interactions between multiple software intermediaries.

API是首字母缩略词,代表应用程序编程接口,根据维基百科,应用程序编程接口(API)是计算接口,它定义了多个软件中介之间的交互。

What that definition basically means is that APIs allow your web application to communicate with other web applications. This “communication” can be best explained with an example specific to the project we are going to build.

该定义的基本含义是API允许您的Web应用程序与其他Web应用程序进行通信。 可以通过一个特定于我们要构建的项目的示例来最好地解释这种“交流”。

For this project, we will be using the Unsplash API to create an image gallery. We are using the API to communicate with Unsplash (Unsplash.com). In this communication, we are making a “request” to Unsplash’s server to get access to some of their images, so we can use them for our image gallery.

对于此项目,我们将使用Unsplash API创建图片库。 我们正在使用API​​与Unsplash(Unsplash.com)进行通信。 在此通信中,我们向Unsplash的服务器发出“请求”以访问其某些图像,因此我们可以将其用于我们的图像库。

The most important part to take note of here is that we are using the API to get access to Unsplash’s images for us to use in our project; what this means is that we can use an API to get data from an outside source which is very cool and very useful.

这里要注意的最重要部分是,我们正在使用API​​来访问Unsplash的图像,以供我们在项目中使用。 这意味着我们可以使用API​​从外部资源获取数据,这非常酷而且非常有用。

图片库入门 (Getting Started with our Image Gallery)

Before we can get started with using the API, we have to set up a basic structure for our project. For this project we will need a code editor to write our code in. I personally recommed the Visual Studio Code editor but you can use any code editor you want to do this.

在开始使用API​​之前,我们必须为我们的项目建立一个基本结构。 对于这个项目,我们将需要一个代码编辑器来编写我们的代码。我个人建议使用Visual Studio代码编辑器,但是您可以使用任何想要执行此操作的代码编辑器。

Open up the code editor of your choice and create a directory (folder) with the title “unsplash_api_gallery”. Inside the directory you need the following three files:

打开您选择的代码编辑器,并创建一个标题为“ unsplash_api_gallery”的目录(文件夹)。 在目录中,您需要以下三个文件:

  • index.html

    index.html
  • index.css

    index.css
  • index.js

    index.js

You can look to the picture below for a visual on what it should look like

您可以查看下面的图片,以直观了解其外观

An image of a file directory in visual studio code. The file directory is called “unsplash_api_gallery” and it has 3 files.
We need these 3 files in our project directory to get us started
我们需要在项目目录中使用这3个文件来开始使用

设置页面的基本结构(Setting up the Basic Structure of our page)

The content of our web page is going to be made up mostly of images generated in our JavaScript file but we do need to set up a basic structure of our web page using some html and css

网页的内容将主要由JavaScript文件中生成的图像组成,但是我们确实需要使用一些html和CSS来设置网页的基本结构

Open up the index.html file in the directory and enter the following:

打开目录中的index.html文件,然后输入以下内容:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <meta name="viewport" content="width=device-width, initial-scale=1.0">  <title>Fancy Car Gallery</title>  <link rel="stylesheet" href="index.css">  <script defer src="index.js"></script></head><body>  <!-- My header here is just for presentation-->   <header>     <h1> Fancy Car Gallery</h1>   </header>   <div id = "img-box">    <!-- I will be populating this div with images from my unsplash api call-->   </div>   <!-- My footer here is just for presentation-->
<footer> <p id = "footer-text"> <span style = "text- decoration:underline;"> Designed & Developed by :</span> Patrick Pierre</p> </footer></body></html>

In the html code above, notice that there is a section of it that says <div id = “img-box”>. This part is important because this is the html tag that will contain all of the images that we will get from our call to the unsplash API. The <header></header> and the <footer></footer> are used in our html for styling purposes. Lastly all the code inside the<head></head> will be used to make sure our html document meets with the web’s best practices and to allow our css file and javascript file to be load.

在上面的html代码中,请注意其中有一段显示<div id = “img-box”> 。 这部分很重要,因为这是html标记,它将包含我们从对unsplash API的调用中获得的所有图像。 <header></header><footer></footer>在我们的html中用于样式目的。 最后, <head></head>内的所有代码都将用于确保我们的html文档符合网络上的最佳做法,并允许加载css文件和javascript文件。

Now open up the index.css file and enter the following:

现在打开index.css文件并输入以下内容:

/* All the flex-related properties are used to help position things on the page */*{
box-sizing: border-box;
}body,html{/*The padding and margin here are 0 so that we don't see any white space around the edges of the header and footer*/ padding:0;
margin:0;
background-color: white;
}body{ display:flex;
flex-direction: column;
flex-wrap: wrap;
}header,footer{ margin:0;
padding:0;
height:200px;
width:auto;
padding: 20px 10px;
background-color:rgba(26,26,26,.7);
display:flex;
flex-direction: column;
justify-content: center;
color:white;}h1{ text-align:center;
font-size:40px;}#img-box{ display:flex;
flex-direction: row;
justify-content: center;
flex-wrap: wrap;
padding:0px;
width: 100%;}#footer-text{ text-align:center;
font-size:25px;}

Since this is project focuses on what we are going to do in our JavaScript code, I won’t get into the specifics of what the css code does but if you want to learn more about css I will provide a great resource you can use at the end of the post.

由于该项目专注于我们将在JavaScript代码中执行的操作,因此我不会详细介绍CSS代码的功能,但是如果您想了解有关CSS的更多信息,我将提供大量资源,您可以在帖子的结尾。

向Unsplash API发出请求 (Making our Request to the Unsplash API)

So we’re finally ready to start working with APIs in our JavaScript file…

因此,我们终于准备好开始使用JavaScript文件中的API了……

But before we get into the code there are a few more things I would like to tell you about using the Unsplash API.

但是在进入代码之前,我想告诉您有关使用Unsplash API的更多信息。

In order to use the Unsplash API in JavaScript, you need to learn how to use the Fetch method and you need to register for an API key.

为了在JavaScript中使用Unsplash API,您需要学习如何使用Fetch方法,并且需要注册API密钥

那么什么是提取方法? (So what is the Fetch Method?)

The Fetch method is a method provided by the Fetch API that is built into the browser. It is used to get access to data through the use of the HTTP protocol,which the system used to transfer files throughout the internet.

Fetch方法是浏览器内置的Fetch API提供的方法。 它用于通过使用HTTP协议来访问数据,该协议用于系统通过Internet传输文件。

Below is a snippet of JavaScript code that will show you the syntax of how to make a request using the Fetch method.

下面是一段JavaScript代码,它将向您展示如何使用Fetch方法发出请求的语法。

const requestUrl = "url of whatever you want to make a request to";fetch(requestUrl)
.then(response => response.json())
.then(data => {
// do something with the data the API has returned
})

Okay now let me explain what is going on in the code above.

好的,现在让我解释一下上面代码中的情况。

In the first line of code we have defined a variable that contains the url of the API we would like to make a request to. In the second line, we started the fetch request with the fetch method. It is important to note that the fetch method takes 2 arguments (the 2nd argument is optional). If we only use one argument the request will default to a GET request; if we use the 2nd argument, we have access to all the other requests types.

在代码的第一行中,我们定义了一个变量,其中包含我们要向其发出请求的API的URL。 在第二行中,我们使用fetch方法启动了fetch请求。 重要的是要注意fetch方法带有2个参数(第2个参数是可选的)。 如果仅使用一个参数,则请求将默认为GET请求;否则,默认为GET。 如果使用第二个参数,则可以访问所有其他请求类型。

So let’s just say we decided to log the result of fetch(requestUrl) with a valid url as an argument to the browser console using console.log(). When logged to the console we will get back a promise object. A promise is a special JavaScript Object, that will allow us to receive our data from the fetch request if it is successful or execute some snippet of code if the requested data fails to get back to us.

因此,假设我们决定使用console.log()将带有有效url的fetch(requestUrl)结果记录为浏览器控制台的参数。 登录到控制台后,我们将返回一个Promise对象。 promise是一个特殊JavaScript对象,如果成功,它将允许我们从提取请求中接收数据,或者如果请求的数据未能返回给我们,则执行一些代码片段。

Since our fetch returns a promise object, we have access to the following three methods:

由于我们的提取操作返回了一个Promise对象,因此我们可以使用以下三种方法:

  • .then(callback) which is is used when the promise is fulfilled (success)

    .then(callback)用于实现诺言(成功)时使用

  • .catch(callback) which is used when the promise is rejected (fail)

    .catch(callback) ,当承诺被拒绝(失败)时使用

  • .finally(callback) happens on both a fulfilled and rejected promise

    .finally(callback)发生在已实现和已拒绝的承诺上

In the above code snippet we use .then() to allow our code to do something with a successful promise. Our .then() method, and all other methods of promise objects, takes a callback function as an argument. It is considered best practice to use an ES6 arrow function as a callback function so we use it in both of our .then() methods.

在上面的代码片段中,我们使用.then()允许我们的代码成功完成承诺。 我们的.then()方法以及其他所有.then()对象方法,都使用回调函数作为参数。 将ES6箭头函数用作回调函数被认为是最佳实践,因此我们在两个.then()方法中都使用了它。

As you might have noticed, we chained two .then() method onto our fetch request; the reason why we did this is because the result of calling our first .then()on the promise returned from fetch()is actually another promise object!

您可能已经注意到,我们将两个.then()方法链接到了我们的提取请求上。 之所以这样做,是因为对从fetch()返回的promise调用第一个.then()的结果实际上是另一个promise对象!

Because our .then() returns another promise object, we have to use another .then() on it to get access to our data from our api request.

由于我们的.then()返回另一个promise对象,因此我们必须在其上使用另一个.then()才能从api request中访问我们的数据

Lastly I would like you to look at the callback functions inside each of the .then() method invocations . Inside the first .then() we put:

最后,我希望您查看每个.then()方法调用内的回调函数。 在第一个.then()里面.then()我们放入:

response => response.json()

response => response.json()

What this does is allow us to get access to our data from the second promise in the form of a JavaScript object.

这样做是为了让我们能够以JavaScript对象的形式从第二个承诺中访问数据。

You need to include this part in your fetch request in order to get back the data you want as a result for you to use in the callback of your second .then()

您需要在获取请求中包含此部分,以便取回您想要在第二个.then()回调中使用的结果数据。

如何在Unsplash上​​注册API密钥? (How do I register for an API key on Unsplash?)

Now that we finished covering how to use the fetch method, the last thing we need is to register for an API key on Unsplash’s website. We need an API key in order to make fetch requests to Unsplash’s API.

现在我们已经完成了如何使用fetch方法的工作,我们需要做的最后一件事是在Unsplash网站上注册API密钥。 我们需要一个API密钥才能对Unsplash的API进行提取请求。

The API key will provide us with authorization to use Unsplash’s data. In order to get your API key click here, and choose the option that says “register as a developer”. Once you register, you should be given access to your unique API key.

API密钥将为我们提供使用Unsplash数据的授权。 为了获得您的API密钥,请单击此处,然后选择“注册为开发者”选项。 注册后,您应该可以访问自己的唯一API密钥。

API keys are as important as the password to your phone or bank account so make sure that you do not make your API keys publically available or share them with anyone. What this means is that if you ever wanted to host this project or to use an API in a future website or application, you will need to look into how to hide your API keys properly.

API密钥与手机或银行帐户的密码一样重要,因此请确保您不要公开使用API​​密钥或将其与任何人共享。 这意味着如果您想托管此项目或在将来的网站或应用程序中使用API​​,则需要研究如何正确隐藏API密钥。

A great resource on how to do that will be provided at the end of the post, so let’s move on.

文章结尾将提供有关如何执行此操作的大量资源,让我们继续。

最后让我们提出要求 (Let’s Finally Make Our Request)

Below is code snippet of the JavaScript code used for this project

以下是此项目使用JavaScript代码的代码段

const divForImg = document.getElementById("img-box");//enter your api key where it says YOUR_ACCESS_KEYconst requestOne = "https://api.unsplash.com/search/photos?page=1&query=&const requestTwo = "https://api.unsplash.com/search/photos?page=2&query=expensive-cars&function makeRequestToUnsplash(requestUrl){  fetch(requestUrl)
.then( res => res.json())
.then((data) => { //we are actually using the returned data from the API here
// data.results contains an array of objects so we can use an array method here to iterate data.results.forEach( (imageObj) =>{
createImage(imageObj);
}); });
}// the function createImage() below is a helper function used to generate an image tag for use in our web pagefunction createImage(imageObj){ const imageDiv = document.createElement("div");
const image = document.createElement("img"); // styling for the elements image.src = imageObj.urls.regular;
image.alt = imageObj.alt_description;
image.style.margin = "20px";
image.style.width = "600px";
image.style.height = "500px";
image.style.border = "double 4px black"
imageDiv.append(image);
divForImg.append(imageDiv);}//each call to makeRequestToUnsplash() returns data with 10 images in it
//so I make two calls to it to get 20 images to populate the page with imagesmakeRequestToUnsplash(requestOne);
makeRequestToUnsplash(requestTwo);

Now let me explain what the code in this snippet is doing.

现在,让我解释一下此代码段中的代码在做什么。

In the first line we got access to the following tag in our html code: <div id = "img-box"></div> . We need this because this is where our images will be added in the page. In the next two lines we create 2 variables to store two different api calls to the unsplash API.

在第一行中,我们可以访问html代码中的以下标记: <div id = "img-box"></div> 。 我们需要这样做,因为这是将图像添加到页面中的位置。 在接下来的两行中,我们创建2个变量来存储对unsplash API的两个不同的api调用。

Let’s take a closer look at the string stored inside our requestOne variable. Inside it, we have a string of the url of a request to be used inside the fetch method. The main url used in all requests to the Unsplash API is https://api.unsplash.com and it is used in every API call that we make to Unsplash. Everything we put after the main url is called an API endpoint, and each endpoint will allow us to access a different piece of Unsplash’s database.

让我们仔细看一下存储在我们的requestOne变量中的字符串。 在其中,我们有一个要获取的字符串,用于fetch方法中。 在所有对Unsplash API的请求中使用的主要网址https://api.unsplash.com ,该https://api.unsplash.com在我们对Unsplash进行的每个API调用中都使用。 我们在主url之后添加的所有内容都称为API端点,每个端点将使我们能够访问Unsplash数据库的不同部分。

The endpoint that we are using in requestOne will allow us to search unsplash’s database for a specific key word and return 10 pictures associated with that key word. The key word that we are using in our search is “expensive cars”. The second request we make has the same keyword in its search but gets 10 different pictures than what the first request returns.

我们在requestOne中使用的端点将使我们能够在unsplash的数据库中搜索特定的关键字,并返回与该关键字相关的10张图片。 我们在搜索中使用的关键词是“昂贵的汽车”。 我们发出的第二个请求在搜索中具有相同的关键字,但与第一个请求返回的内容相比,得到10张不同的图片。

It is important to note here than when we have access to our data from the second .then() , we should make sure to log the result of that data to the console to see what kind of data structure we are working with. This is a great practice to have as you should always be checking to see what form your data comes in.

重要的是要在此处进行说明,而不是从第二个.then()访问数据时,应确保将数据结果记录到控制台,以查看我们正在使用哪种数据结构。 这是一个好习惯,因为您应该经常检查数据的输入格式。

Inside our second .then() method we call a function that we made later in our code that takes the data from unsplash and uses it to create an image tag <img> with an image source, alt text and some basic styling. The reason why called our function here is because this is the only point in which we can use the data that we requested.

在第二个.then()方法中,我们调用一个稍后在代码中创建的函数,该函数从未飞溅的数据中获取数据,并使用它来创建具有图像源,替代文本和一些基本样式的图像标签<img> 。 之所以在这里调用我们的函数,是因为这是我们可以使用所请求的数据的唯一点。

Adding this code snippet will make our page look like this:

添加此代码段将使我们的页面如下所示

Image for post
This is a screen shot of what our project will look like after the code in our JavaScript file is run
这是运行JavaScript文件中的代码后我们的项目外观的屏幕截图

现在轮到你了(Now it’s Your Turn)

If you got this far and followed along, you have successfully made your own fetch request to a real API….yay

如果您已经走了这么远并且一直遵循,那么您已经成功向真正的API发出了自己的提取请求….yay

Now that you’ve done that it’s your turn to make the project your own. One of the most important things you can do to get the most out of project based learning is to add something of your own to the project.

现在您已经完成了,现在就该使该项目成为您自己的了。 要充分利用基于项目的学习,可以做的最重要的事情之一就是向项目添加自己的东西。

So I challenge you to add something extra to the project to make it your own. If you don’t know what to add here are some suggestions:

因此,我要求您为项目添加一些额外的内容以使其成为您自己的项目。 如果您不知道要添加什么,请参考以下建议:

  • Make some request to some of Unsplash’s other API endpoints

    向Unsplash的其他API端点提出一些请求
  • Take this project and make it into a full website

    将此项目纳入完整的网站
  • Add some additonal JavaScript feature that you would like to see on a page like this

    添加一些您希望在这样的页面上看到的其他JavaScript功能

其他资源(Additional Resources)

As Promised here are some more resources to help you understand this topic

如所承诺的,这里有更多资源可帮助您理解本主题。

More about Promises:

有关承诺的更多信息:

javascript.info explanation of promises

javascript.info承诺说明

More about fetch:

有关获取的更多信息:

Documentation about fetch

有关获取的文档

A Great Resource on How to Hide API Keys:

有关如何隐藏API密钥的重要资源:

If you enjoyed this post and would like to see other small tutorials like this one, please share this post and let me know what you think of it in the comment section.

如果您喜欢这篇文章,并希望看到其他类似的小型教程,请分享这篇文章,并在评论部分告诉我您的想法。

Feel free to reach out to me on Twitter as well if you have any questions about this post, I would love to hear from you.

如果您对此帖子有任何疑问,请随时通过Twitter与我联系,我希望收到您的来信。

翻译自: https://medium.com/@patrick.pierre000/making-use-of-apis-in-your-front-end-c168e343bea3

前端使用api连接后端的吗

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值