通过准将Fluffykins学习Node.js第三部分:请求对象,配置路由,服务文件

by Mariya Diminsky

通过玛丽亚·迪明斯基(Mariya Diminsky)

通过准将Fluffykins学习Node.js第三部分:请求对象,配置路由,服务文件 (Learn Node.js with Brigadier Fluffykins Part III: Request Object, Configure Routes, Serve Files)

Welcome to Part III of Learn Node.js With Brigadier Fluffykins, a series created to help you easily understand Node.js ❤

欢迎使用Fluffykins准将学习“学习Node.js”的第三部分,该系列旨在帮助您轻松理解Node.js❤

In Part II Brigadier Fluffykins and I walked you through how Node.js is an event driven language. You learned how this is important for asynchronous behavior, and how these events are processed via the Event Loop. You also learned how DOM events and events in Node.js are similar. Lastly, we created our first EventEmitter.

第二部分中 ,我和Fluffykins准将向您介绍Node.js如何成为事件驱动的语言。 您了解了这对于异步行为的重要性,以及如何通过Event Loop处理这些事件。 您还了解了DOM事件和Node.js中的事件如何相似。 最后,我们创建了第一个EventEmitter

Let’s move on to the next lesson! OH YEAH!!

让我们继续下一课! 哦耶!!

Today’s we’ll learn about:

今天,我们将了解:

  • Types of request methods

    请求方法的类型
  • The Request Object

    请求对象

  • Configuring multiple routes

    配置多条路由
  • Difference between setHeader and writeHead

    setHeaderwriteHead之间的区别

  • How to serve files (HTML, CSS, etc.)

    如何提供文件(HTML,CSS等)
请求方法的类型 (Types of Request Methods)

The four main HTTP requests:

四个主要的HTTP请求:

  • GET — Used when the client is requesting data. For example, when they are asking to view your homepage, they will need the HTML, CSS, and JavaScript documents. These are all GET requests.

    GET —在客户端请求数据时使用。 例如,当他们要求查看您的主页时,他们将需要HTML,CSS和JavaScript文档。 这些都是GET请求。
  • POST — Used when the client is submitting data to the server or to a database. For example, submitting a form.

    POST —在客户端将数据提交到服务器或数据库时使用。 例如,提交表格。
  • PUT — Similar to POST, but not used much. Use this when you are changing something at a specific URL or updating a resource in the server. The main difference is that PUT is idempotent.

    PUT —与POST类似,但使用很少。 在特定URL上更改内容或更新服务器中的资源时,请使用此功能。 主要区别在于PUT是幂等的

  • DELETE — Deletes the specified resource.

    DELETE —删除指定的资源。

GET and POST requests are used most often. PUT and DELETE aren’t used as much. Then there are requests such as HEAD, OPTIONS, and CONNECT. These are used even less often, but good to know just in case.

GET和POST请求最常用。 很少使用PUT和DELETE。 然后有诸如HEAD,OPTIONS和CONNECT之类的请求。 这些的使用频率更低,但以防万一。

Since GET and POST are the most common, we’ll be reviewing these. The GET request will be discussed today, while we’ll discuss the POST method in the next lesson, as it’s going to make more sense then.

由于GET和POST是最常见的,因此我们将对其进行审查。 GET请求将在今天讨论,而我们将在下一课中讨论POST方法,因为届时它将更加有意义。

请求对象 (The Request Object)

When we set up our server, we want the request event to listen for any incoming requests from the client. It’s important to remember that this is not the same as the request object in a callback. Also, the request and response objects look like parameters, and you can even change their names — like I did in the example below from ‘request’ to ‘req’ and ‘response’ to ‘res’ — but they are still objects. Keep that in mind.

设置服务器时,我们希望request 事件侦听来自客户端的所有传入请求。 重要的是要记住,这与回调中的请求对象不同 。 同样,请求和响应对象看起来像参数,甚至可以更改它们的名称(就像我在下面的示例中所做的那样,从“请求”更改为“ req”,将“响应”更改为“ res”),但它们仍然是对象。 记在脑子里。

The request object is huge with many different properties, functions, and methods. Let’s try printing the request object in your terminal. Open up the server.js in the nodestory2 folder. All the files you need for the rest of this lesson will be here.

请求对象巨大,具有许多不同的属性,功能和方法。 让我们尝试在终端中打印请求对象 。 在nodestory2文件夹中打开server.js 。 本课程其余部分所需的所有文件都将在此处。

Before continuing, Brigadier Fluffykins and I want you to know:

在继续之前,弗拉维金准将和我希望您知道:

If you feel overwhelmed by the amount of code in the zip folder, especially the server.js file — I know I did when I first started learning Node.js — just take a breather and know that we’ve got your back. We’ll be walking you through each section, step by step. Take as much time as you need.

如果您对zip文件夹中的代码量感到不知所措,尤其是server.js文件-我知道我刚开始学习Node.js的时候就做过-喘口气,就知道我们已经支持您。 我们将逐步引导您完成每个部分。 根据需要花费尽可能多的时间。

Perseverance is key to progress in programming, and in life. Also, constantly save your file and restart the server if you made any changes in the file. Good luck! :)

毅力是编程和生活进步的关键。 另外,如果您对文件进行了任何更改,请不断保存文件并重新启动服务器。 祝好运! :)

You can also just create your own file with the same name — server.js and copy and paste this in:

您也可以只创建自己的同名文件-server.js并将其复制并粘贴到:

Kudos if you know what to do next.

如果您知道下一步该怎么做,则表示荣誉。

Locate your server.js file or the nodestory2 folder you downloaded. In the example below I went to my Desktop, then the nodestory2 folder then inside that folder was the server.js file.

找到您的server.js文件或下载的nodestory2文件夹。 在下面的示例中,我转到了我的桌面,然后是nodetory2文件夹,然后在该文件夹内是server.js文件。

Type in node server.js in the shell, go to http://localhost:3000/, and you should see the request object in your shell:

在外壳程序中输入node server.js ,转到http:// localhost:3000 / ,您应该在外壳程序中看到请求对象

The screenshot above is after I’ve scrolled all the way up to the beginning.

上面的屏幕截图是在我一直滚动到最开始之后。

It’s ginormous right?

这是巨大的吧?

The request object is an instance of the IncomingMessage object. You can read more about that here if you’re interested.

请求对象IncomingMessage对象的实例。 如果您有兴趣,可以在这里阅读更多信息。

Throughout this series, we will discuss the more commonly-used properties of the request object, especially since you’ll probably only be using a handful of them in your projects.

在整个系列中,我们将讨论request对象更常用的属性,尤其是因为您可能仅在项目中使用其中的少数几个。

The url and method properties are two that frequently work together. When we set up our server and have these two properties, we are saying “Hey server, if you see that the client is coming from this URL and they want information back (GET method), then trigger the callback”.

urlmethod属性是两个经常一起使用的属性。 当我们设置服务器并具有这两个属性时,我们说的是“嘿,服务器,如果您看到客户端来自此URL,并且他们希望返回信息 (GET方法),然后触发回调”。

When you print the url and method properties of the request object what do you get? Comment out STEP #2 and uncomment STEP #2.1. Or copy and paste this into your server.js file:

当您打印请求对象urlmethod属性时,您会得到什么? 注释掉步骤2,并取消注释步骤2.1。 或将其复制并粘贴到您的server.js文件中:

Remember, as I mentioned in Part I, any time you make changes inside of a server file, you have to restart the server again for it to work properly. To stop the server manually go into your terminal and press control + C for Mac (again, I believe it’s killall node for Windows).

请记住,就像我在第一部分中提到的那样,每次在服务器文件中进行更改时,都必须重新启动服务器才能使其正常工作。 要手动停止服务器,请进入终端并在Mac上按Control + C (同样,我相信这是Windows的killall节点 )。

Now type node server.js in the shell to start the server, then go to http://localhost:3000/, and you should see something like this in your shell:

现在,在外壳程序中键入node server.js来启动服务器,然后转到http:// localhost:3000 / ,您应该在外壳程序中看到以下内容:

The request URL printed ‘/’. This is the URL for where the client is coming from, in this case the homepage — also called the ‘root directory’. And the request method printed ‘GET’, meaning the client wanted to view or get the necessary files for the page.

请求网址打印为“ /”。 这是客户端来自的URL,在本例中为主页,也称为“根目录”。 请求方法显示为“ GET”,这表示客户端希望查看或获取页面所需的文件。

If you get a second GET request, it’s most likely for the favicon in your browser that’s automatically requested by default.

如果您收到第二个GET请求,则很可能是默认情况下会自动请求浏览器中的收藏夹图标。

The headers method is also quite useful, as it gives us information about where the request is coming from. This including browsing info, cookies, and more.

标头方法也非常有用,因为它为我们提供了有关请求来自何处的信息。 这包括浏览信息,Cookie等。

Let’s try printing the headers and then accessing one. Be aware that it comes as an object of key value pairs. Uncomment STEP #2.2 and comment out STEP #2.1 or copy and paste this into your server.js file:

让我们尝试打印标题,然后访问其中一个。 请注意,它是键值对的对象。 取消注释步骤#2.2并注释掉步骤#2.1或将其复制并粘贴到您的server.js文件中:

Restart the server. You should get an object of headers in your shell.

重新启动服务器。 您应该在外壳程序中获得标头对象。

If you get two objects, again, probably that favicon, and thus a second header object was printed, just ignore it for now.

如果您再次得到两个对象(可能是那个图标),并因此打印了第二个标题对象,请暂时将其忽略。

It’s important to note that if you are receiving headers that are the same name they will either be overwritten or presented as a string separated by commas, depending on the type of header it is.

重要的是要注意,如果您接收的标题相同,则标题将被覆盖或显示为以逗号分隔的字符串,具体取决于标题的类型。

If you really want the exact headers that exist — even if they have the same names (possibly because you need their different values) — you can use the rawHeaders method. So you would enter req.rawHeaders instead of req.headers.

如果您确实想要存在的确切标头(即使它们具有相同的名称(可能因为您需要使用不同的值)),则可以使用rawHeaders方法。 因此,您将输入r eq.rawHeaders而不是req.headers

Try it out! See what you get :)

试试看! 看看你得到什么:)

配置多条路由 (Configuring Multiple Routes)

This URL: / means the home page. To access a different page, we create a new GET request with a different name after the forward slash.

此URL: /表示主页。 要访问其他页面,我们用斜杠后的名称创建一个新的GET请求。

Let’s review everything we’ve learned so far and create two GET requests — one if the client is requesting the homepage and another one if they are requesting the /blueberries page. Why blueberries? It doesn’t actually matter. If you know the client is going to go to www.yourhomepage.com/blueberries then you know that you have to create a request in your server for /blueberries so when they type that URL path, they will see some content instead of an error message.

让我们回顾一下到目前为止我们已经学到的所有内容,并创建两个GET请求-一个如果客户端正在请求主页,则另一个,如果他们正在请求/ blueberries页面,则另一个。 为什么要蓝莓? 实际上并不重要。 如果您知道客户端将要访问www.yourhomepage.com/blueberries,那么您就必须在服务器中为/ blueberries创建一个请求,这样当他们键入该URL路径时,他们将看到一些内容而不是错误信息。

The truth is, Brigadier Fluffykins demonstrated his ninja skills to me and in payment, I had to choose that URL path:

事实是,准将Fluffykins向我展示了他的忍者技能,在付款方面,我不得不选择该URL路径:

Otherwise, it wouldn’t actually matter. Let’s continue:

否则,这实际上并不重要。 让我们继续:

Comment out STEP #2.2 and uncomment STEP #2.3 or just copy and paste this into your server.js file. Don’t forget to save after:

注释掉STEP#2.2并取消注释STEP#2.3,或者将其复制并粘贴到server.js文件中。 不要忘了保存以下内容:

Now restart the server and go to http://localhost:3000/, you should see this:

现在重新启动服务器,并转到http:// localhost:3000 / ,您应该看到以下内容:

Ok good, now let’s try out the other request we configured. Go to http://localhost:3000/blueberries. You should see this:

好的,现在让我们尝试配置的其他请求。 转到http:// localhost:3000 / blueberries 。 您应该看到以下内容:

Do you see what happened there? We can change /blueberries to anything we want, as long as we configure what the client should see. So if you went to http://localhost:3000/something or http://localhost:3000/somethingelse, it wouldn’t work unless we created responses for these requests in our server.

你看到那里发生了什么吗? 只要我们配置客户端应看到的内容,我们就可以将/ blueberries更改为所需的任何内容。 因此,如果您访问了http:// localhost:3000 / somethinghttp:// localhost:3000 / somethingelse 除非我们在服务器中为这些请求创建了响应,否则它将无法正常工作。

Let’s demonstrate this by changing one line in our code. Change this line:

让我们通过更改代码中的一行来演示这一点。 更改此行:

if (req.url === '/blueberries') {

To this:

对此:

if (req.url === '/carrots') {

Save and restart your server. Now go to: http://localhost:3000/blueberries

保存并重新启动服务器。 现在转到: http:// localhost:3000 / blueberries

See how it no longer works? Go to http://localhost:3000/carrots

看看它不再起作用了吗? 转到http:// localhost:3000 / carrots

It should work now because we have a response configured for the /carrots path, while the path for /blueberries no longer exists (unless we choose to create it).

现在应该可以正常工作,因为我们为/ carrots路径配置了响应,而/ blueberries的路径不再存在(除非我们选择创建它)。

setHeader和writeHead之间的区别 (The difference between setHeader and writeHead)

The setHeader method takes a name as its first parameter, and a value for its second. You can call this method multiple times in the same request, but make sure you don’t include invalid characters or you’ll receive an error — specifically, a TypeError.

setHeader方法将名称作为其第一个参数,并将其值作为第二个参数。 您可以在同一请求中多次调用此方法,但请确保不包含无效字符,否则会收到错误-特别是TypeError

Let’s try this out, change your home page request to this:

让我们尝试一下,将您的主页请求更改为:

Save and restart the server.

保存并重新启动服务器。

You should see the new headers on the homepage in your Network tab.

您应该在“网络”标签的首页上看到新的标题。

To access your Network tab, right click → inspect → choose the Network tab(in the same row as Console).

要访问“网络”选项卡,请右键单击→检查→选择“网络”选项卡(与“控制台”在同一行)。

Or on a mac: Cmd + Option + J → Network tab.

或在Mac上:Cmd + Option + J→网络选项卡。

It’s not particular useful to set random headers, but if you’re working with authentication or cookies in the browser, setHeader is part of that process.

设置随机标头并不是特别有用,但是如果您正在浏览器中使用身份验证或cookie,则setHeader就是该过程的一部分。

In our last lesson we set the header via writeHead method. There we set the status code. The difference between setHeader and writeHead is that setHeader sets one header at a time, and you can use as many setHeader methods as you need before you send the response.

上一课中,我们通过writeHead方法设置标头。 在那里,我们设置状态代码。 setHeaderwriteHead之间的区别是setHeader一次设置一个标头,并且可以在发送响应之前根据需要使用任意数量的setHeader方法。

On the other hand, writeHead can set the status code (first parameter), and multiple headers inside of an object (the second parameter) at the same time.

另一方面, writeHead可以同时设置状态码(第一个参数)和对象内部的多个标头(第二个参数)。

Setting the status code manually helps ensure that the page will load correctly. If you include setHeader and writeHead in the same request, they will merge together with writeHead taking precedence. This also means any headers with the same name in both setHeader and writeHead will be overwritten by writeHead headers.

手动设置状态代码有助于确保页面正确加载。 如果在同一请求中包含setHeaderwriteHead ,则它们将与writeHead合并在一起。 这也意味着setHeaderwriteHead中具有相同名称的任何标头都将被writeHead标头覆盖。

如何提供文件 (How to Serve Files)

Have you noticed how our responses have only been plain words and simple HTML? As a developer you will often serve actual documents, so let’s learn how to do that!

您是否注意到我们的答复仅是纯文字和简单HTML? 作为开发人员,您通常会提供实际的文档,因此让我们学习如何做!

Either paste this into your server.js or uncomment STEP #2.4 and comment out STEP #2.3. Can you guess what’s happening here?

将此粘贴到您的server.js或取消注释步骤#2.4并注释掉步骤#2.3。 你能猜出这里发生了什么吗?

This should be in your index.html file:

这应该在您的index.html文件中:

…and this little snippet should be in your style.css file:

…这个小片段应该在您的style.css文件中:

.see-me { background-color: black;}

Take a look at the code in server.js on STEP #2.4. Read through the code comments and see if you can understand what’s going on before continuing.

在STEP#2.4上查看server.js中的代码。 通读代码注释,看看在继续之前是否可以理解正在发生的事情。

readFile is a method of the file system, one of Node.js’s core modules, which we briefly covered in Part I. And that’s why we required that module in our code and stored it in the fs variable. It will read the file asynchronously and trigger the callback. When the callback is triggered, the file is inside of it. So the next thing we did was send it to the client using the end method.

readFile文件系统的一种方法它是Node.js的核心模块之一,我们在第一部分中进行了简要介绍。 这就是为什么我们在代码中需要该模块并将其存储在fs变量中的原因。 它将异步读取文件并触发回调。 触发回调后,文件就在其中。 因此,我们接下来要做的就是使用end方法将其发送给客户

You can also send over .js files — and even JSON — just don’t forget to set the Content-Type headers to avoid errors. For example for a .js file, the Content-Type should be set to application/javascript. These are also known as the MIME types.

您还可以发送.js文件(甚至JSON) ,只是不要忘记设置Content-Type标头以避免错误。 例如,对于.js文件,应将Content-Type设置为application / javascript 。 这些也称为MIME类型。

__dirname basically means the current directory of the server.js file. More on paths, modules and libraries in the next lesson!

__dirname基本上表示server.js文件的当前目录。 在下一课中将详细介绍路径,模块和库!

Did you notice how we configured the request for the style.css?

您是否注意到我们如何配置style.css的请求?

Why do you think we need to do this?

您为什么认为我们需要这样做?

Most likely the client won’t be typing in yourwebsite.com/style.css. The client just wants your style.css to automatically be there so that your HTML page looks great right? You could test it out and visit localhost:3000/style.css and you’ll see it there, but how do we get it sent to the client automatically?

客户端很可能不会输入yourwebsite.com/style.css。 客户端只希望您的style.css自动存在,以便您HTML页面看起来不错吧? 您可以对其进行测试并访问localhost:3000 / style.css,然后在其中看到它,但是我们如何将其自动发送到客户端?

You probably remember making HTML pages and including your CSS in a different file. To get that CSS to work, we needed to include the CSS link tag inside of the html page. We already did this in index.html:

您可能还记得制作HTML页面并将CSS包含在其他文件中。 为了使CSS能够正常工作,我们需要在html页面中包含CSS 链接标签。 我们已经在index.html中做到了:

<link rel="stylesheet" href="style.css">

So now when a client requests the index.html page, the server will scan the code inside index.html for any other important tags such as the link (CSS files) or script (JavaScript files) tags.

因此,现在当客户端请求index.html页面时,服务器将扫描index.html内的代码以查找其他任何重要标记,例如链接 (CSS文件)或脚本 (JavaScript文件)标记。

In our case we only included the CSS page. It will find this link tag and essentially this is like sending an automatic GET request. Basically the servers are like:

在我们的案例中,我们仅包含CSS页面。 它将找到此链接标记,从本质上讲,这就像发送自动GET请求一样。 基本上,服务器就像:

“Hey look, the client wants the HTML page! OK, let me check if this HTML page has anything else I need to send. Oh look, a link tag for the file style.css! That must mean there is a css page for this html page. Ok let’s go back into my server.js file. Yep! I have a response for this CSS file too, so I’ll be serving back both the HTML file and CSS files!”

“嘿,客户想要HTML页面! 好的,让我检查一下此HTML页面是否还有其他需要发送的内容。 哦,看,这是文件style.css链接标记! 那必须意味着该html页面有一个CSS页面。 好的,让我们回到我的server.js文件。 是的 我也对此CSS文件有回应 ,因此我将同时提供HTML文件和CSS文件!”

If you visit the home page now and open the Network tab, you should see the CSS working properly. If you don’t see it right away, refresh the browser. And if you still don’t see it, make sure you saved the file and restarted the server:

如果现在访问主页并打开“网络”选项卡,则应该看到CSS正常工作。 如果您没有立即看到它,请刷新浏览器。 如果仍然看不到,请确保已保存文件并重新启动服务器:

Otherwise, if we didn’t configure the style.css request in our server.js, only the HTML page would be sent and we would see an error in our network tab for the style.css page.

否则,如果我们未在server.js中配置style.css请求,则只会发送HTML页面,并且在style.css页面的网络标签中会看到错误。

We may also experience abnormally long load times because the server is searching for the configuration of the style.css. It would be thinking:

由于服务器正在搜索style.css的配置,我们可能还会经历异常长的加载时间。 会在想:

“I see that the HTML file has a link tag but I can’t find any response for this CSS file in server.js. I don’t get it. Where is it? Where is it?”

“我看到HTML文件具有链接标记,但在server.js中找不到此CSS文件的任何响应 。 我不明白 它在哪里? 它在哪里?”

And I’d like to close today’s lesson with a nifty little trick. It may look intimidating at first, especially if it’s your first time seeing regex. I just wanted to share this handy snippet with you anyway in case in the near future you’re setting up an app and all it needs is to serve files that end with .js, .html, or .css. instead of writing multiple requests.

我想用一个漂亮的小技巧来结束今天的课程。 乍看起来可能令人生畏,尤其是这是您第一次看到regex时 。 我只是想与您分享这个方便的代码段,以防在不久的将来您要建立一个应用程序,而它所需要的只是提供以.js,.html或.css结尾的文件 而不是编写多个请求。

It’s OK if you don’t understand it right away — just save it for later and come back to it when you’re ready! It’s good to have in your back pocket :)

如果您不立即理解它也可以-只需将其保存以供日后使用,然后在准备好后再返回即可! 放在后兜里很好:)

if (request.url.match(/.js$|.html$|.css$/)) {  return response.end(fs.readFileSync(__dirname + '/..' +   request.url));}
查看这些额外的资源 (Check out these extra resources)

Congrats! You’ve made it through Learn Node.js With Brigadier Fluffykins Part III! You learned about the different request types, how to configure GET requests at different URLs, and how to serve files!

恭喜! 您已经通过Fluffykins准将学习Node.js取得了成功 ! 您了解了不同的请求类型,如何在不同的URL配置GET请求,以及如何提供文件!

On top of all this you should now have a basic understanding of the request object, and some useful methods! Great job today!

最重要的是,您现在应该对r equest对象以及一些有用的方法有了基本的了解! 今天干得好!

We’ll learn more about these topics as well as others we’ve only scratched in the next few lessons. Thank you for reading and stay tuned.

在接下来的几课中,我们将学习有关这些主题以及我们仅涉及的其他主题的更多信息。 感谢您的阅读和关注。

Keep your wisdom up to date by clicking the ❤ below and following, as more Learn Node.js With Brigadier Fluffykins is coming soon to Medium!

单击下面的❤,保持您的最新知识,更多信息了解Fluffykins与Brigadier Fluffykins即将发布!

Part I: Sync, Async, and Creating Your First Server!

第一部分:同步,异步和创建您的第一台服务器!

Part II: Events, EventEmitter & Event Loop

第二部分:事件,EventEmitter和事件循环

Part III: Request Object, Configure Routes, Serve Files

第三部分:请求对象,配置路由,服务文件

翻译自: https://www.freecodecamp.org/news/learn-node-js-with-brigadier-fluffykins-part-iii-request-object-configure-routes-serve-files-7666f783dc10/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值