API’s Study Notes: How To Make A

作者: 此之木 | 来源:发表于2019-10-06 04:44 被阅读0次

The course shows us we can make API’s requests with Node.

The first thing we need to do is to create the “APIs” directory and touch “request.js” file inside that folder.

Then, we need to npm install request package in the APIs directory.

Once we have done those basic steps, we can start to require the “request” and make a request from a JavaScript file.

In the request, we need to have the“url”, so the server knows where it should request the API. Next, we need to have a function.

request(“url”, function(error, response, body)

In the function, there are three things we pass in: error, response, and body.

Error:it will hold any potential error that we get such as internet disconnect, 404, and etc. It is important to check for an error.

Response: it will be the incoming message that we receive

Body: it is the actual response body that came back like HTML code

For example, in the “request.js” file, I make a fake URL in the request, and I write an if statement to check error.

If there is an error, it will print out the error. Else if the response status code is equal to 200, which means the request was received is fine to process, we can print out the body.

Since this URL is a fake one, the request won’t be processed correctly. Therefore, the server print out the error message.

Now, I put my personal WordPress blog URL in the request, and run the server. Since my URL is correct, so the server can receive the response and process it. As a result, we can see it print out the WordPress blog HTML code.

相关文章

网友评论

    本文标题:API’s Study Notes: How To Make A

    本文链接:https://www.haomeiwen.com/subject/exqotctx.html