了解如何使用 NodeJS 创建一个简单的后端
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18597140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Understanding how to use NodeJS to create a simple backend
提问by Janis F
I have been trying to develop a rather simple server in nodejs. Basically, what I am going for is a simple API that requires authentication (simple username/password style). What I do notneed is any kind of frontend functionality (templating etc.). My problem is, I can't seem to get my head around the approach of express/node.
Specifically, my questions are:
我一直在尝试在 nodejs 中开发一个相当简单的服务器。基本上,我想要的是一个需要身份验证的简单 API(简单的用户名/密码样式)。我要做的不是需要的是任何类型的前端功能(模板等)。我的问题是,我似乎无法理解 express/node 的方法。
具体来说,我的问题是:
- How do I wire in the authentication? Do I pass several handlers into every route that requires authentication, or is there a more elegant way to do this?
- How does the Express middleware (like
app.use(express.bodyParser())) work? Do they alter contents of therequestorresponseobject? Specifically, if I use the body parser (internally formidable?), where do I access the request data this is supposed to parse? - When using authentication and I have, say, credentials stored in a database with more information about the individual client associated, at what point do I extract that information? I.e., when a user logs in, do I fetch the user record on login and pass it on, or do I fetch it in every handler that requires the information?
- Ultimately, do you know of an open source application that I could take a look at? I'd like to see something that has simple authentication and maybe even utilizes formidable, since uploading a file is one of my requirements.
- 如何进行身份验证?我是否将多个处理程序传递到需要身份验证的每个路由中,或者是否有更优雅的方法来执行此操作?
- Express 中间件(如
app.use(express.bodyParser()))如何工作?它们会改变request或response对象的内容吗?具体来说,如果我使用正文解析器(内部强大?),我在哪里访问应该解析的请求数据? - 当使用身份验证时,例如,我将凭据存储在数据库中,其中包含有关相关单个客户端的更多信息,我应该在什么时候提取该信息?即,当用户登录时,我是在登录时获取用户记录并传递它,还是在每个需要该信息的处理程序中获取它?
- 最后,您知道我可以查看的开源应用程序吗?我希望看到一些具有简单身份验证甚至可能使用强大功能的东西,因为上传文件是我的要求之一。
As I mentioned earlier, I believe my problem is ultimately a difficulty with the function-oriented approach in node (also, I have rather limited experience in webservice programming). If you know a resource where I could read up on how to approach architecting a nodejs app, please don't hesitate to point me to it.
正如我之前提到的,我相信我的问题最终是 node 中面向函数的方法的一个困难(而且,我在 web 服务编程方面的经验相当有限)。如果您知道我可以阅读有关如何构建 nodejs 应用程序的资源,请不要犹豫,将其指向我。
采纳答案by Krasimir
How do I wire in the authentication? Do I pass several handlers into every route that requires authentication, or is there a more elegant way to do this?
如何进行身份验证?我是否将多个处理程序传递到需要身份验证的每个路由中,或者是否有更优雅的方法来执行此操作?
You should use the session middleware. Here is some pseudo code:
您应该使用会话中间件。下面是一些伪代码:
var http = require('http');
var app = express();
var authorize = function(req, res, next) {
if(req.session && req.session.appname && req.session.appname === true) {
// redirect to login page
return;
}
next();
}
app.use(express.session());
app.all('/admin*', authorize, function(req, res, next) {
});
How does the Express middleware (like app.use(express.bodyParser())) work? Do they alter contents of the request or response object? Specifically, if I use the body parser (internally formidable?), where do I access the request data this is supposed to parse?
Express 中间件(如 app.use(express.bodyParser()))如何工作?他们是否改变了请求或响应对象的内容?具体来说,如果我使用正文解析器(内部强大?),我在哪里访问应该解析的请求数据?
Every middleware have an access to the request and response object. So, yes, it modifies it. Normally attach properties to it. This means that inside your handler (which is also a middleware) you may write:
每个中间件都可以访问请求和响应对象。所以,是的,它修改了它。通常将属性附加到它。这意味着在您的处理程序(也是一个中间件)中,您可以编写:
if(req.body && req.body.formsubmitted && req.body.formsubmitted === 'yes') {
var data = {
title: req.body.title,
text: req.body.text,
type: req.body.type
}
// store the data
}
When using authentication and I have, say, credentials stored in a database with more information about the individual client associated, at what point do I extract that information? I.e., when a user logs in, do I fetch the user record on login and pass it on, or do I fetch it in every handler that requires the information?
当使用身份验证时,例如,我将凭据存储在数据库中,其中包含有关相关单个客户端的更多信息,我应该在什么时候提取该信息?即,当用户登录时,我是在登录时获取用户记录并传递它,还是在每个需要该信息的处理程序中获取它?
I think that you should do the things the same way as in any other server side language. Keep the state of the user (logged/not-logged) inside a session. You may also keep the user's id and fetch the data for him whatever you need. It depends of your case, but you have the ability to cache information. Because node is not like PHP for example, I mean it's not dieing.
我认为您应该以与任何其他服务器端语言相同的方式来做这些事情。在会话中保持用户的状态(已记录/未记录)。您还可以保留用户的 id 并根据需要为他获取数据。这取决于您的情况,但您可以缓存信息。例如,因为 node 不像 PHP,所以我的意思是它不会消亡。
Ultimately, do you know of an open source application that I could take a look at? I'd like to see something that has simple authentication and maybe even utilizes formidable, since uploading a file is one of my requirements.
最后,您知道我可以查看的开源应用程序吗?我希望看到一些具有简单身份验证甚至可能使用强大功能的东西,因为上传文件是我的要求之一。
Yep. I wrote an article about really simple MVC web site with admin panel. It is available here. And the code of it is here.
回答by Jazor
A simple way to implement authentication (if you don't want to use additional modules):
实现身份验证的简单方法(如果您不想使用其他模块):
var checkAuth = function(req, res, next) {
if(!req.session.user)
{
// Redirect to login form
res.redirect("/login");
}
else
{
// Proceed to member's area
next();
}
};
app.get("/member/page", checkAuth, function(req, res) {
// render view, etc
});
bodyParserparses / converts the body of a POST request into an object, which helps with getting form submission values.
bodyParser将 POST 请求的正文解析/转换为对象,这有助于获取表单提交值。
The route that handles your login form submission can access username / password like this:
处理登录表单提交的路由可以像这样访问用户名/密码:
var username = req.body.username;
var password = req.body.password;
At this point you'd query your database to select from users where the username and password matches (you'd want to use password encryption in a production environment).
此时,您将查询数据库以从用户名和密码匹配的用户中进行选择(您希望在生产环境中使用密码加密)。
If you get a record back in the query result, set it in the session. A simple way to do this is:
如果您在查询结果中得到一条记录,请在会话中设置它。一个简单的方法是:
req.session.user = userRecord
(Adjust for your session middleware)
(针对您的会话中间件进行调整)
回答by deitch
If you are looking for REST, I recommend using either Restifyor booster
如果您正在寻找 REST,我建议您使用Restify或booster
For authentication(distinct from authorization), use standard Basic, which can be handled by express.basicAuth()just to parse it and place it on the reqobject. Personally, I don't like basicAuthbecause it returns a 401if there is no login, whereas the process of authenticatingis different than determining if authentication is necessary.
对于身份验证(与授权不同),请使用标准 Basic,express.basicAuth()只需解析它并将其放置在req对象上即可处理。就我个人而言,我不喜欢basicAuth它,因为它401在没有登录时返回 a ,而身份验证的过程与确定是否需要身份验证不同。
For more advanced authentication, as well as session management, use cansecurityor passport. For authorization, you either can put individual middleware in each route, use cansecurity's middlewares, or use its declarative authorization.
对于更高级的身份验证以及会话管理,请使用cansecurity或通行证。对于授权,您可以在每个路由中放置单独的中间件,使用 cansecurity 的中间件,或者使用其声明式授权。
Disclosure: I am the author of both booster and cansecurity.
披露:我是 booster 和 cansecurity 的作者。
回答by Leprosy
If your goal is to build a RESTful API in Node.js, my best bet would be Restify, which uses a similar aproach of routes like Express, but eliminates all the high level stuff(templating, etc.) and ads backend functionalities(ie: body parser, ip blacklist, requests per hour).
如果您的目标是在 Node.js 中构建 RESTful API,我最好的选择是Restify,它使用类似 Express 的路由方法,但消除了所有高级内容(模板等)和广告后端功能(即:正文解析器、IP 黑名单、每小时请求数)。
For the authentication part, I would use another library perhaps, and wire it to a particular route. There are ORM's too that can solve your database needs(mongo and mysql are well supported, both for the "noSQL" fans and the classic db aproach ones).
对于身份验证部分,我可能会使用另一个库,并将其连接到特定路由。也有 ORM 可以解决您的数据库需求(mongo 和 mysql 得到了很好的支持,无论是“noSQL”粉丝还是经典的 db 方法)。

