gpt4 book ai didi

javascript - 了解如何使用 NodeJS 创建一个简单的后端

转载 作者:数据小太阳 更新时间:2023-10-29 05:19:17 26 4
gpt4 key购买 nike

我一直在尝试用 nodejs 开发一个相当简单的服务器。基本上,我想要的是一个需要身份验证的简单 API(简单的用户名/密码样式)。我不需要需要的是任何类型的前端功能(模板等)。我的问题是,我似乎无法理解 express/node 的方法。

具体来说,我的问题是:

  • 如何进行身份验证?我是将多个处理程序传递到每条需要身份验证的路由,还是有更优雅的方法来执行此操作?
  • Express 中间件(如 app.use(express.bodyParser()))如何工作?它们是否改变了 requestresponse 对象的内容?具体来说,如果我使用主体解析器(内部功能强大?),我应该在哪里访问应该解析的请求数据?
  • 当使用身份验证时,例如,我将凭据存储在数据库中,其中包含有关关联的各个客户端的更多信息,我在什么时候提取该信息?即,当用户登录时,我是在登录时获取用户记录并传递它,还是在每个需要该信息的处理程序中获取它?
  • 最后,您是否知道我可以查看的开源应用程序?我希望看到具有简单例份验证的东西,甚至可能使用强大的东西,因为上传文件是我的要求之一。

正如我之前提到的,我相信我的问题最终是 Node 中面向功能的方法的困难(另外,我在 web 服务编程方面的经验相当有限)。如果您知道我可以阅读有关如何构建 nodejs 应用程序的资源,请毫不犹豫地指出我。

最佳答案

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?

您应该使用 session 中间件。这是一些伪代码:

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?

每个中间件都可以访问请求和响应对象。所以,是的,它修改了它。通常将属性附加到它。这意味着在你的处理程序(它也是一个中间件)中你可以这样写:

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?

我认为您应该像在任何其他服务器端语言中那样做这些事情。将用户的状态(已登录/未登录)保存在 session 中。您还可以保留用户的 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.

是的。我写了一篇关于带有管理面板的非常简单的 MVC 网站的文章。可用here .它的代码是here .

关于javascript - 了解如何使用 NodeJS 创建一个简单的后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18597140/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com