如何在不使用框架的情况下通过Node.js将MongoDB中的数据显示到前端 [英] How to display data from MongoDB to the frontend via Node.js without using a framework

查看:127
本文介绍了如何在不使用框架的情况下通过Node.js将MongoDB中的数据显示到前端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Node.js和编程的新手。这是我的第一个服务器端语言,我需要你的帮助。 我确实有html / css / javascript经验。我也知道如何使用FileSystem和request.url流通过NodeJS提供html页面。

I am new to Node.js and programming in general. This is my first server side language and I need your help. I do have html/css/javascript experience. I also know how to serve up html pages via NodeJS using FileSystem and the request.url stream.

*问题:*
如何在不使用Express或任何其他框架的情况下查询和显示Mongo DB中的数据到html页面? Pure Node.JS / Javascript **

我宁愿不使用Express,因为我首先想要掌握Node.JS。

I rather not use Express because I am trying to master Node.JS first.

我尝试研究PHP的做法,并发现他们的过程是这样的:

I tried studying PHP's way of doing it, and found their process to to be like this :

连接数据库:

$con=mysqli_connect("example.com","peter","abc123","my_db");

查询数据库:

$result = mysql_query("SELECT * FROM names");

显示结果:

<?php echo $result; ?>

Node.js如何连接/查询/从数据库显示到前端?不使用像EXPRESS这样的框架

推荐答案

这是我在本地主机上运行的代码,它正在运行罚款。

here is my code which I have run in my localhost, and it is working fine.

代码

const http = require('http');
const port = 8080;
const hostname = 'localhost';

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost:27017/testDB', {
   useCreateIndex: true,
   useNewUrlParser: true
});

var schema = new mongoose.Schema({
   firstName: String,
   lastName: String
})

var userSchema = mongoose.model("user", schema);

http.createServer((req, res) => {
   userSchema.find().then((result, err) => {
       res.writeHead(200, { 'Content-Type': 'application/json' });
       res.end(JSON.stringify({status: 200, message: 'data retrive 
           successfully' data : result}));
  })
}).listen(port, () => {
   console.log(`your server are listing http://${hostname}:${port}`);
})

我希望它能帮到你,创建服务器不使用nodeJS中的express框架。

I hope it will help you, To create a server without using the express framework in nodeJS.

这篇关于如何在不使用框架的情况下通过Node.js将MongoDB中的数据显示到前端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆