qcloud+mpvue+koa1.1.3无法路由

发布于 2022-09-07 20:14:40 字数 9607 浏览 11 评论 0

src/me.vue下的scanBook方法是能正常获取图书的ISBN的,问题出在同页面下的async addBook 方法种,正常登录后,添加图书的时候,怎么都触发不了/weapp/addbook的路由,试了N种方法,目录server/controllers/addbook.js路由配置了,但实际运行中根本访问不到,相当郁闷.

相关代码

// Me.vue

<template>
  <div class="container">
    <div class="userinfo">
      <img :src="userinfo.avatarUrl">
      <p>{{userinfo.nickName}}</p>
    </div>
    <YearProgress></YearProgress>

    <button v-if='userinfo.openId' @click='scanBook' class='btn'>添加图书</button>
    <button v-else open-type="getUserInfo" lang="zh_CN" class='btn' @getuserinfo='login' >点击登录</button>
  </div>
</template>

<script>
import qcloud from 'wafer2-client-sdk'
import YearProgress from '@/components/YearProgress'
import {showSuccess, post} from '@/util'
import config from '@/config'

export default {
  components: {
    YearProgress
  },
  data () {
    return {
      userinfo: {
        avatarUrl: 'http://image.shengxinjing.cn/rate/unlogin.png',
        nickName: ''
      }
    }
  },
  methods: {
     async addBook (isbn) {
      console.log(isbn)
      const res = await post('/weapp/addbook',{
        isbn,
        openid:this.userinfo.openId
      })
      // showModal('添加成功',`${res.title}添加成功`)
    },
    scanBook () {
      wx.scanCode({
        success: (res) => {
          if (res.result) {
            this.addBook(res.result)
          }
        }
      })
    },

    getWxLogin: function ({encryptedData, iv, userinfo}) {
      const self = this
      wx.login({
        success: function (loginResult) {
          console.log('loginResult', loginResult)
          var loginParams = {
            code: loginResult.code,
            encryptedData: encryptedData,
            iv: iv
          }
          qcloud.setLoginUrl(config.loginUrl)
          qcloud.requestLogin({
            loginParams,
            success () {
              // 获取用户信息
              qcloud.request({
                url: config.userUrl,
                login: true,
                success (userRes) {
                  showSuccess('登录成功')
                  wx.setStorageSync('userinfo', userRes.data.data)
                  self.userinfo = userRes.data.data
                }
              })
            },
            fail (error) {
              console.log(error)
              // showModal('登录失败', error)
            }
          })
        },
        fail: function (loginError) {
          // showModal('登录失败', error)
          console.log(loginError)
        }
      })
    },

    login (e) {
      const self = this
      // 查看是否授权
      wx.getSetting({
        success: function (res) {
          // 授权信息里有用户信息
          if (res.authSetting['scope.userInfo']) {
            // 检查用户登录是否过期
            wx.checkSession({
              success: function () {
                // 没过期 直接成功
                showSuccess('登录成功')
              },
              fail: function () {
                // 过期了 重新登录 先清除登录的状态
                qcloud.clearSession()
                // 登录状态已过期 需要重新登录
                // 登录需要的加密信息
                var options = {
                  encryptedData: e.mp.detail.encryptedData,
                  iv: e.mp.detail.iv,
                  userinfo: e.mp.detail.userInfo
                }
                self.getWxLogin(options)
              }
            })
          } else {
            // showModal('用户未授权', e.mp.detail.errMsg)
            console.log('用户未授权', e.mp.detail.errMsg)
          }
        }
      })
    }
  },
  onShow () {
    let userinfo = wx.getStorageSync('userinfo')
    if (userinfo) {
      this.userinfo = userinfo
    }
  }
}
</script>

<style lang='scss'>
.container{
  padding:0 30rpx;

  .userinfo{
    margin-top: 100rpx;
    text-align: center;
    img {
      width: 150rpx;
      height: 150rpx;
      margin: 20rpx;
      border-radius: 50%
    }
  }
}
</style>
wafer2-quickstart-nodejs-master插件的server目录,my-project/server/routes/index.js
/**
 * ajax 服务路由集合
 */
const router = require('koa-router')({
    prefix: '/weapp'
})
const controllers = require('../controllers')

// 从 sdk 中取出中间件
// 这里展示如何使用 Koa 中间件完成登录态的颁发与验证
const { auth: { authorizationMiddleware, validationMiddleware } } = require('../qcloud')

// --- 登录与授权 Demo --- //
// 登录接口
router.get('/login', authorizationMiddleware, controllers.login)
// 用户信息接口(可以用来验证登录态)
router.get('/user', validationMiddleware, controllers.user)

// --- 图片上传 Demo --- //
// 图片上传接口,小程序端可以直接将 url 填入 wx.uploadFile 中
router.post('/upload', controllers.upload)

// --- 信道服务接口 Demo --- //
// GET  用来响应请求信道地址的
router.get('/tunnel', controllers.tunnel.get)
// POST 用来处理信道传递过来的消息
router.post('/tunnel', controllers.tunnel.post)

// --- 客服消息接口 Demo --- //
// GET  用来响应小程序后台配置时发送的验证请求
router.get('/message', controllers.message.get)
// POST 用来处理微信转发过来的客服消息
router.post('/message', controllers.message.post)

router.get('/demo', controllers.demo)
router.post('/addbook', controllers.addbook)
module.exports = router
wafer2-quickstart-nodejs-master插件的server目录,my-project/server/controllers/addbook.js
const https = require('https')

module.exports = async (ctx) => {
    const { isbn, openid } = ctx.request.body
    console.log('添加图书', isbn, openid)
    if (isbn && openid) {
        let url = 'https://api.douban.com/v2/book/isbn/' + isbn
        console.log(url)
        const bookinfo = await getJSON(url)
        const rate = bookinfo.rating.average
        const { title, image, alt, publisher, summary, price } = bookinfo
        console.log(bookinfo)
    } else {
        console.log(22222)
    }
}

function getJSON (url) {
    return new Promise((resolve, reject) => {
        https.get(url, res => {
            let urlData = ''
            res.on('data', data => {
                urlData += data
            })
            res.on('end', data => {
                const bookinfo = JSON.parse(data)
                if (bookinfo.title) {
                    resolve(bookinfo)
                }
                reject(bookinfo)
            })
        })
    })
}
项目主配置json
{
  "name": "mpvue-demo",
  "version": "1.0.0",
  "description": "A Mpvue project",
  "author": "3581729170@qq.com",
  "private": true,
  "scripts": {
    "dev": "node build/dev-server.js",
    "start": "node build/dev-server.js",
    "build": "node build/build.js",
    "lint": "eslint --fix --ext .js,.vue src"
  },
  "dependencies": {
    "mpvue": "^1.0.11",
    "vuex": "^3.0.1",
    "wafer2-client-sdk": "^1.1.3"
  },
  "devDependencies": {
    "babel-core": "^6.22.1",
    "babel-eslint": "^8.2.3",
    "babel-loader": "^7.1.1",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "babel-register": "^6.22.0",
    "chalk": "^2.4.0",
    "connect-history-api-fallback": "^1.3.0",
    "copy-webpack-plugin": "^4.5.1",
    "css-loader": "^0.28.11",
    "cssnano": "^3.10.0",
    "eslint": "^4.19.1",
    "eslint-config-standard": "^11.0.0",
    "eslint-friendly-formatter": "^4.0.1",
    "eslint-loader": "^2.0.0",
    "eslint-plugin-html": "^4.0.3",
    "eslint-plugin-import": "^2.11.0",
    "eslint-plugin-node": "^6.0.1",
    "eslint-plugin-promise": "^3.4.0",
    "eslint-plugin-standard": "^3.0.1",
    "eventsource-polyfill": "^0.9.6",
    "express": "^4.16.3",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^1.1.11",
    "friendly-errors-webpack-plugin": "^1.7.0",
    "glob": "^7.1.2",
    "html-webpack-plugin": "^3.2.0",
    "http-proxy-middleware": "^0.18.0",
    "mpvue-loader": "1.0.13",
    "mpvue-template-compiler": "^1.0.11",
    "mpvue-webpack-target": "^1.0.0",
    "node-sass": "^4.9.2",
    "optimize-css-assets-webpack-plugin": "^3.2.0",
    "ora": "^2.0.0",
    "portfinder": "^1.0.13",
    "postcss-loader": "^2.1.4",
    "postcss-mpvue-wxss": "^1.0.0",
    "prettier": "~1.12.1",
    "px2rpx-loader": "^0.1.10",
    "rimraf": "^2.6.0",
    "sass-loader": "^7.0.3",
    "semver": "^5.3.0",
    "shelljs": "^0.8.1",
    "uglifyjs-webpack-plugin": "^1.2.5",
    "url-loader": "^1.0.1",
    "vue-style-loader": "^4.1.0",
    "webpack": "^3.11.0",
    "webpack-bundle-analyzer": "^2.2.1",
    "webpack-dev-middleware-hard-disk": "^1.12.0",
    "webpack-merge": "^4.1.0",
    "webpack-mpvue-asset-plugin": "0.0.2"
  },
  "engines": {
    "node": ">= 4.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}
项目的config.json
{
    "description": "项目配置文件。",
    "setting": {
        "urlCheck": false,
        "es6": false,
        "postcss": true,
        "minified": true,
        "newFeature": true
    },
    "miniprogramRoot": "./dist/",
    "qcloudRoot": "./server/",
    "compileType": "miniprogram",
    "appid": "wx73a95869c3086bce",
    "projectname": "mpvue-demo",
    "condition": {
        "search": {
            "current": -1,
            "list": []
        },
        "conversation": {
            "current": -1,
            "list": []
        },
        "game": {
            "currentL": -1,
            "list": []
        },
        "miniprogram": {
            "current": -1,
            "list": []
        }
    }
}
完整代码包在这里(包括可以识别的图书二维码)-----> 百度网盘

请哪位知道的,指点下问题出在哪里?谢谢!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

还给你自由 2022-09-14 20:14:40

知道什么问题了,nnd,手误,util里的函数参数位置写颠倒了

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文