
node.js 搭建简单后端项目,express中使用POST,调用外部API,连接数据库
node.js 搭建简单后端项目,express中使用POST,调用外部API,连接数据库1、创建目录并初始化2、安装express3、安装body-parser (express中使用POST)4、安装axios (express 调用外部api)5、新建index.js6、新建router.js 对请求的处理,express中使用POST/请求外部接口7、启动项目8、项目启动后台持续运行,使用
·
node.js 搭建简单后端项目,express中使用POST,调用外部API,连接数据库
1、创建目录并初始化
mkdir node-server && cd node-server && npm init -y
2、安装express
npm install express --save
3、安装body-parser (express中使用POST)
npm install body-parser
4、安装axios (express 调用外部api)
npm install axios
5、新建index.js
const express = require('express')
const app = express()
const bodyParser = require('body-parser')
const router = require('./router')//引用模块
// parse application/x-www-form-urlencoded
//配置模板引擎body-parser一定要在app.use(router)挂载路由之前
app.use(bodyParser.urlencoded({extended: false}))
// parse application/json
app.use(bodyParser.json())
// 全局 中间件 解决所有路由的 跨域问题
app.all('*', function (req, res, next) {
res.header('Access-Control-Allow-Origin', '*')
res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type')
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT')
res.header('Access-Control-Allow-Credentials', true);
res.header("Content-Type", "application/json;charset=utf-8");
next()
})
app.use(router)
app.listen(3033, function () {
console.log("中间服务已启动!监听端口3033")
})
6、新建router.js 对请求的处理,express中使用POST/请求外部接口
//创建路由
const {Router} = require('express')
const router = new Router()
const axios = require("axios")
const api = 'http://192.168.1.116:8000/api/'
router.post('/inrecognition', (request, response) => { //处理post请求
let obj = {
deviceId: request.body.deviceId,
deviceName: request.body.deviceName,
}
axios.post(api + 'inrecognition', obj) //请求外部接口
.then((res) => {
response.send(res.data)
})
.catch((error) => {
console.error(error)
response.send(error)
})
})
module.exports = router
7、启动项目
node index.js
或在package.json scripts 添加启动项
添加 "start": "node ./index.js"
后可通过 npm run start
或 npm start
启动项目
8、项目启动后台持续运行,使用pm2
全局安装pm2
npm install pm2 -g
启动 (也可配置到package.json中)
pm2 start index.js
9、连接mysql数据库
下载mysql依赖
npm install mysql
新建 mysql.js 连接数据库
const mysql = require("mysql")
const Dbs = {
host: 'localhost',
user: 'root',
password: 'root',
database: 'mydb'
}
const connection = mysql.createConnection(Dbs)
connection.connect()
// //查询
// connection.query(`sql`, (err, rows, fields) => {
// if (err) throw err
// console.log(rows)
// })
//
//
// connection.end()
module.exports = connection
在需要调用的文件中引入使用,如在router.js引入
const mysql = require('./mysql')
调用
router.get('/getsomething', (req, res) => {
mysql.query(`select * from deviceinfo limit 3`, (err, rows, fields) => {
if (err) throw err
res.send(rows)
})
})
10、其他
其它Node.js连接数据库方法参考 https://www.cnblogs.com/joyo-w/p/10660952.html
express中文文档:https://express.nodejs.cn/
拓展:KOAJS https://koa.bootcss.com/
更多推荐
所有评论(0)