Nodejs入门 [实现http请求服务和操作Mysql数据库]

nodejs是一门服务端的语言,同时也是现在前端必须要会的一门语言。

简单地说,node.js就是运行在服务端的javascript。本文通过实现http请求响应和连接数据库进行增删改查来直观的体会一下node.js

1.导入http请求模块

const http = require('http');

这是nodejs内嵌的API,所以可以直接使用,就像是python里import包一样。

2.创建一个httpserver服务

http.createServer(function(request,response){})

3.添加输出内容

response.end("<strong>hello server!!</strong>");

 这个语句要加在httpserver服务的回调函数中

4.为浏览器添加解析

response.writeHead(200,{'Content-type':'text/html'});

因为浏览器不认识什么是hello server,所以我们要让浏览器认识它,就要告诉浏览器将以text-html去解析hello server这段数据,以html方式解析浏览器就知道strong标签什么意思了。同样这个语句要写在回调函数中。

5.添加监听端口

这里结合前两个语句把创建的httpserver服务补全:

http.createServer(function(request,response) {
    response.writeHead(200,{'Content-type':'text/html'})
    response.end("<strong>hello server!!</strong>");
}).listen(8888);

这里我们的http请求的端口号是8888

最后我们整理一下完整的http请求服务代码:

const http = require('http');
http.createServer(function(request,response) {
    response.writeHead(200,{'Content-type':'text/html'})
    response.end("<strong>hello server!!</strong>");
}).listen(8888);
console.log("您启动的服务是: http://localhost:8888已启动成功");

6.启动运行服务

在集成终端中运行:

 看到这句话就说明我们的http请求服务成功了

在浏览器中输入:http://localhost:8888/qu'fang'wen

可以看到浏览器中输出了加粗了的hello server

 

回到第四步,如果我们把 'text/html' 改为 'text/plain' ,也就是文本解析,浏览器中会输出什么呢?

注意:我们修改操作后要保存js文件,在终端中重新输入前要按 Ctrl+c才行

我们重新启动服务再刷新浏览器:

可以看到如果我们告诉浏览器以文本解析的话,strong标签会原封不动的输出出来。那么这就是我们学习nodejs的第一个入门案例了。

下面我们学习一下用node来操作数据库

nodejs的官方文档里没有给我们提供操作数据库的模块,那怎么办呢?我们可以引入第三方的模块

1.安装mysql依赖 

npm install mysql

 我们在项目工程的终端里直接执行这个命令就行:

然后在我们的项目目录中就多了一个node_modules文件夹:

2.导入mysql依赖包

var mysql = require("mysql");

3.配置数据连接信息

mysql.createConnection({
    host:"127.0.0.1",
    post:3306,
    user:"root",
    password:'111',
    database:"testdb"
});

这里host就是我们的本机ip,post是数据库端口,user是用户名,然后就是密码,database是我们建立的数据库:

我们建完数据库之后,在里面新建一个表,这里就叫user了,然后向表里插入两条数据: 

4. 创建一个mysql的connection对象

我们定义一个connection变量来对连接的信息进行接收:

var connection = mysql.createConnection({
    host:"127.0.0.1",
    post:3306,
    user:"root",
    password:'111',
    database:"testdb"
});

5.开辟连接

connection.connect();

6.执行语句

connection.query("select * from user",function(error,results,fields) {
    //如果查询出错,直接抛出
    if(error)throw error;
    //查询成功
    console.log("results = ",results);
})

这里我们直接查询一下数据库里的所有数据,然后把results结果集输出出来

7.关闭连接

connection.end();

把所有部分整理一下:

var mysql = require("mysql");
var connection = mysql.createConnection({
    host:"127.0.0.1",
    post:3306,
    user:"root",
    password:'111',
    database:"testdb"
});
connection.connect();
connection.query("select * from user",function(error,results,fields) {
    if(error)throw error;
    console.log("results = ",results);
})
connection.end();

8.运行并查看结果

可以看到在终端中输出了我们在数据库中添加的所有数据

这样通过nodejs操作数据库我们也简单实现了。

猜你喜欢

转载自blog.csdn.net/qq_49900295/article/details/124136722