前端开发与数据库开发_如果您是前端开发人员,如何设置数据库

前端开发与数据库开发

by Andrea Zanin

由Andrea Zanin

如果您是前端开发人员,如何设置数据库 (How to set up a database if you’re a front-end developer)

Someone recently asked me what’s the easiest way for a front-end developer to save users’ data. So I am going to explain how to do just that.

最近有人问我,前端开发人员保存用户数据的最简单方法是什么。 因此,我将解释如何做到这一点。

设置数据库 (Setting up the database)

The first thing we will need is an actual database. You can head to mlab for a free one. Once you’ve signed up, click create new in the MongoDB Deployments tab. The sandbox database is free of charge, so that’s the one we are going to use.

我们需要的第一件事是一个实际的数据库。 您可以免费获得mlab 。 注册后,点击新建 在MongoDB部署选项卡中。 沙盒数据库是免费的,因此我们将使用它。

Once we’ve created the database, we need to create an account so that we can authenticate ourselves. Click on the database name, then users, and add database user. Write down the username and password you chose since we will need them later.

创建数据库后,我们需要创建一个帐户,以便对自己进行身份验证。 点击数据库名称,然后点击用户, 添加数据库用户 。 写下您选择的用户名和密码,因为稍后我们将需要它们。

On top of the database’s page, you should see a MongoDB URI. This is the web address of our database. The URI of your database is like the URL for a web page. By convention, the MongoDB URI is as follows:

在数据库页面的顶部,您应该看到一个MongoDB URI。 这是我们数据库的网址。 数据库的URI类似于网页的URL。 按照约定,MongoDB URI如下:

mongodb://<dbuser>:<dbpassword>@<host&gt;:<port>/<dbname>

Mine, for example, is:

例如,我的是:

mongodb://admin:superSecretPassword@ds111885.mlab.com:11885/medium

设置服务器 (Setting up the server)

We are going to use Node in our back end. To avoid having to set it up, you can clone my project on Glitch by clicking here

我们将在后端使用Node。 为避免设置,您可以通过单击此处在Glitch上克隆我的项目

Have a look at the starting server.js file I provided:

看一下我提供的起始server.js文件:

We start by importing express — it’s the library we will use to handle requests to our server.

我们从导入express开始-这是我们用来处理对服务器的请求的库。

We need use(require(cors)) to allow cross-domain requests. Those are requests from a website hosted on a domain to a server on another domain.app.use(require('body-parser').json()) automatically parses the request to JSON for us.

我们需要use(require(cors))来允许跨域请求。 这些是从托管在一个域上的网站到另一个域上的服务器的请求。 app.use(require('body-parser').json())自动为我们解析到JSON的请求。

Then we pass to the get method the route we want to handle and the callback that will handle it. This means that whenever someone opens the page / of our website, the request will be handled by that callback. The base domain is implicit, so if your domain is http://shiny-koala.glitch.com, the route /about will be http://shiny-koala.glitch.com/about.

然后,将要处理的路由以及将要处理的回调传递给get方法。 这意味着只要有人打开我们网站的页面/ ,该请求就会由该回调处理。 基本域是隐式的,因此,如果您的域是http://shiny-koala.glitch.com, 路线/about是http://shiny-koala.glitch.com/about

To be precise, when I say “open the page,” I mean it makes a request using the GET method to our server. Http methods are just types of requests you can make to a server. We will only use the following:

确切地说,当我说“打开页面”时,是指它使用GET方法向我们的服务器发出请求。 Http方法只是您可以向服务器发出的请求类型。 我们将仅使用以下内容:

  • GET This method is used to fetch resources from a server. For example, when you open Facebook, it loads the HTML, CSS, and JavaScript needed.

    GET此方法用于从服务器获取资源。 例如,当您打开Facebook时,它将加载所需HTML,CSS和JavaScript。

  • POST This method is used to create resources on a server. For example, when you post something on Facebook, the information that you wrote in that post is sent to Facebook’s servers in a POST request.

    POST此方法用于在服务器上创建资源。 例如,当您在Facebook上发布内容时,您在该帖子中编写的信息会通过POST请求发送到Facebook的服务器。

  • PUT This method is used to update resources on a server. For example, when you edit a post, your edits are sent to Facebook’s server in a PUT request.

    PUT此方法用于更新服务器上的资源。 例如,当您编辑帖子时,您的编辑将在PUT请求中发送到Facebook的服务器。

The app.post and app.put work exactly like app.get , but handle the POST and PUT method instead of GET quite reasonably.

app.postapp.put工作酷似app.get ,但处理POST和PUT方法,而不是GET的相当合理。

路由 (Routing)

While you develop the server, you will need to do some tests. To run HTTP requests, you can use the handy site REST test test or the Insomnia application.

开发服务器时,需要进行一些测试。 要运行HTTP请求,您可以使用方便的站点REST测试测试Insomnia应用程序。

To check the URL of your Glitch app click the show button.

要检查您的Glitch应用程序的URL,请单击显示按钮。

So far, we have been using only the route / . But we want to store different information about different users, so we need a different route for each user.For example: /ZaninAndrea and /JohnGreen

到目前为止,我们仅使用路线/ 。 但是我们要存储有关不同用户的不同信息,因此我们需要为每个用户使用不同的路由,例如/ZaninAndrea/JohnGreen

Now we have a problem: we can’t possibly code every single route since it’s not a very scalable approach. What we need are route parameters. We will only code one route: /:user

现在我们遇到了一个问题:由于它不是一种非常可扩展的方法,因此我们不可能对每条路线进行编码。 我们需要的是路线参数。 我们将只编码一条路线: /:user

The colon is telling Express to catch any route starting with / and then only alphanumeric characters.

冒号告诉Express捕获任何以/开头,然后仅字母数字字符的路由。

Some examples:

一些例子:

  • /ZaninAndrea will be caught

    /ZaninAndrea将被抓

  • /Johnny45 will be caught

    /Johnny45将被抓

  • /alex/score will not be caught

    /alex/score不会被捕获

We can then retrieve the value of user in the variable request.params.user

然后,我们可以在变量request.params.user检索user的值。

Our server now responds to every query echoing back the username.

现在,我们的服务器会响应每个查询,并返回用户名。

向数据库添加数据 (Adding data to the database)

We know who the user is, and now we want to be able to store some info about him.

我们知道用户是谁,现在我们希望能够存储有关他的一些信息。

To query the database, we will use the mongodb library. You can install it one of two ways:

要查询数据库,我们将使用mongodb库。 您可以通过以下两种方式之一安装它:

npm install mongodb --save

or if you are using Glitch, go to the package.json file and click the button Add package.

或者,如果您使用的是Glitch,请转到package.json文件,然后点击添加软件包按钮。

Let’s load the library and store the MongoDB URI in a variable:

让我们加载库并将MongoDB URI存储在变量中:

The URI is very sensitive information — it’s all that’s needed to access your database. It’s best to put it in a .env file that will not be visible to others.

URI是非常敏感的信息-这是访问数据库所需的全部信息。 最好将其放在一个对他人不可见的.env文件中。

Glitch will automatically load the variables from the .env file to the process.env variable.

Glitch会将变量从.env文件自动加载到process.env变量。

The connection to the database is an asynchronous operation, so we need to wrap all the server setup in a callback like this:

与数据库的连接是异步操作,因此我们需要将所有服务器设置包装在一个回调中,如下所示:

Databases are organized in collections, and collections contain documents (basically JSON files). So let’s connect to the user collection (it will be created the first time we access it).

数据库按集合进行组织,集合包含文档(基本上是JSON文件)。 因此,让我们连接到user集合(它将在我们第一次访问它时创建)。

First, we are going to handle the POST route. That is the one we will use when we add data about a user for the first time. Then we will use the PUT route to update it.

首先,我们要处理POST路由。 那就是我们第一次添加有关用户的数据时将使用的那个。 然后,我们将使用PUT路由进行更新。

The collection.insertOne method adds a new document to the collection. In our case, every user will have its own document.

collection.insertOne方法将一个新文档添加到集合中。 在我们的案例中,每个用户都有自己的文档。

{ ...request.body, user : request.params.user } leverages the spread operator to merge the data provided through the body of the request and the user provided through the URL.

{ ...request.body, user : request.params.user }利用传播运算符合并通过请求正文提供的数据和通过URL提供的用户。

The result is the document that will be stored in the collection.

结果是将存储在集合中的文档。

The second argument is a callback, and simply notifies the user about the result of the operation.

第二个参数是一个回调,仅将操作结果通知用户。

从数据库获取数据 (Getting data from the database)

Now that we have some data on the server, we want to be able to read it. We use the GET method to do this.

现在我们在服务器上有一些数据,我们希望能够读取它。 我们使用GET方法执行此操作。

This time, the first argument is a filter telling the database to only send us the documents with the correct user property.

这次,第一个参数是一个过滤器,该过滤器告诉数据库仅向我们发送具有正确用户属性的文档。

The docs are returned to the user in an array, because there could theoretically be more than one document with that user property. It’s up to us to ensure that this doesn’t happen.

这些文档将以数组的形式返回给用户,因为从理论上讲,可能存在多个具有该用户属性的文档。 我们有责任确保这不会发生。

更新数据库上的数据 (Updating data on the database)

Last but not least is the PUT method that we use to update an already existing user.

最后但并非最不重要的一点是我们用来更新现有用户的PUT方法。

The first argument is a filter, like the one we used in the GET method.

第一个参数是一个过滤器,就像我们在GET方法中使用的一样。

The second argument is an update document — you can read more about them here. In our case, we are telling the database to merge the data passed by the user with the already existing data.

第二个参数是更新文档-您可以在此处阅读有关它们的更多信息。 在我们的例子中,我们告诉数据库将用户传递的数据与现有数据合并。

Be careful though, because nested parameters will be replaced and not merged.

但是请小心,因为嵌套参数将被替换而不是合并。

告别 (Farewell)

This is far from being a complete guide on databases and back-end programming, but it’s enough to get you started and to power personal projects.

这远不是一本完整的数据库和后端编程指南,但是足以让您入门并推动个人项目。

I will probably write about authentication in a future article. Until then, do not use this to store sensitive data.

我可能会在以后的文章中介绍身份验证。 在此之前,请勿使用此存储敏感数据。

You can tinker with the complete project here, you will need your own database tough, if you didn’t create one yet, go back to the section Setting up the database.

您可以在此处修改整个项目,您将需要自己的数据库,如果尚未创建,请回到设置数据库一节。

If you enjoyed this article, please give it some claps so more people see it. Thank you!

如果您喜欢这篇文章,请给它鼓掌,以便更多的人看到。 谢谢!

翻译自: https://www.freecodecamp.org/news/how-to-set-up-a-database-if-youre-a-front-end-developer-3ed945221219/

前端开发与数据库开发

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值