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')
app.use(bodyParser.urlencoded({extended: false}))
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) => {
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()
module.exports = connection
在需要调用的文件中引入使用,如在router.js引入
const mysql = require('./mysql')
调用
router.get('/getsomething', (req, res) => {
mysql.query(`select * from uploaddeviceinfo limit 3`, (err, rows, fields) => {
if (err) throw err
res.send(rows)
})
})
其它Node.js连接数据库方法参考 https://www.cnblogs.com/joyo-w/p/10660952.html
|