express.js调用redis数据库

本文介绍了如何使用Express框架创建一个简单的Node.js项目,包括初始化、添加依赖、配置CORS、连接Redis以及使用Vue组件调用API进行数据交互。
摘要由CSDN通过智能技术生成

1.新建文件夹express-demo

2.npm init 创建node项目

3.package.json加入依赖

{
  "name": "express-demo",
  "version": "1.0.0",
  "description": "node项目",
  "main": "server.js",
  "author": "me",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "redis": "~2.4.2"
  }
}

4.创建server.js文件

const express = require('express')
const cors = require('cors');
const redis = require('redis')
const app = express()
app.use(express.json()); // 设置中间件,将 JSON 格式的请求体自动转换为 JavaScript 对象
// 跨域
app.use(cors({
    origin: 'http://localhost:8088'
}));
const port = 'XXXX'
const host = 'XXXXXXXXXXXXXXXXXXXXXXX'
const auth_pass = 'XXXXXXXXXXXXXXXXXXX'
const client = redis.createClient(port,host,{auth_pass:auth_pass})
client.on('error',(err)=>{
    console.error(err)
})
client.on('connect', () => {
    console.log('Connected to Redis server!')
})
app.get('/get/:key',(req,res)=>{
    if(client.connected)
    {
        client.select(0);
        client.get(req.params.key,(err,data)=>{
            debugger
            if(err){
                console.error(err)
                res.sendStatus(500)
            } else {
                res.send(data)
            }
        })
    }
})


app.post('/set', (req, res) => {
    // 向 Redis 存储数据
    if(client.connected)
    {
        client.select(0);
        client.set(req.body.param1,req.body.param2,(err,data)=>{
            if(err){
                console.error(err)
                res.sendStatus(500)
            } else {
                res.send(data)
            }
        })
    }
})

app.listen(3000,()=>{
    console.log('Server is running on port 3000')
})

5.npm install 引用依赖

6.启用  node server.js

7.调用node服务测试

<template>
  <div style="background: red;">
    <p>{{data}}</p>
  </div>
</template>
<script>
import { defineComponent } from 'vue'
import axios from 'axios'
export default defineComponent({
  name: 'pmtest',
  data() {
    return {
      data: ''
    }
  },
  mounted() {
    axios.get('http://localhost:3000/get/com.hid:cache:project_cache:base:900003508').then((res) => {
      this.data = res.data
    }).catch((err) => {
      debugger
      console.log(err)
    })
    axios.post('http://localhost:3000/set', {
      param1: 'com.hid:cache:project_cache:base:900000000',
      param2: 'value1'
    })
      .then(response => {
        this.data = response.data
      })
      .catch(error => {
        console.error(error)
      })
  }
})
</script>

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值