Home >Web Front-end >JS Tutorial >A brief discussion on how to build a local server using node.js
Using node.jsHow to set up a local server? The following article will introduce to you how to build a local server with node.js. I hope it will be helpful to you!
node.js is a back-end language based on JavaScript. Front-end friends can get started quickly and build a local server by themselves. Let’s take a look at how to do it~
[Recommended study: "nodejs Tutorial"]
Note
: This article You need to understand the add, delete, modify, and query commands of the MySQL database, and you need to manually create a new warehouse and data table
1. Download
official website: node
node -v
in the terminal window. If the node version number appears, the installation is successful2. Simple use
Note
: Use VSCode editor demonstration here, file name Can be customized, it is recommended to use an English name!
Create a new code
folder and open it with the code editor
In the workspace, right-click and select Open
in the integrated terminal and enter npm init -y
to quickly execute npm Initialization
After the initialization is completed, the file package.json
will appear in the workspace, where the downloaded third-party modules
If you are new to npm, it is recommended to execute the following command and use Taobao mirror
to download, which will speed up the download speed of third-party modules
npm config set registry https://registry.npm.taobao.org
Next, start executing the command to download the required third-party modules
npm install express mysql
##1. Connect to the databaseThe code is as follows (example):
New
db.jsIn order for the code structure to be clear and reusable, select a new file here to connect to the mysql database<pre class="brush:php;toolbar:false"> //导出 module.exports = (sql,callback) => { const mysql = require('mysql') const conn = mysql.createConnection({ host:'localhost', // user、password需手动添加,与数据库保持一致 user:'', password:'', database:'数据库名'
}) // 建立连接
conn.connect()
conn.query(sql,callback) // 断开连接
conn.end()
}复制代码</pre>
2. Create a new local serviceThe code is as follows (example):
New
index.js<pre class="brush:php;toolbar:false"> //首先加载express const express = require('express') const app = express() //端口号 const port = 3000 //引入自定义的mysql文件 const db = require('./db.js')
//这里仅列举发送GET请求
app.get('url',(req,res) =>{
db('select * from 表名', (err,result) => { if(err) throw err
res.send(result)
})
})
app.listen(port,() => console.log('server is start,port is', port))复制代码</pre>
3. Test local service
Code editor run
localhostAll are local addresses
Programming Video
! !The above is the detailed content of A brief discussion on how to build a local server using node.js. For more information, please follow other related articles on the PHP Chinese website!