如何在nodejs中为我的api编写app.use()进行vuejs / nodejs firebase部署?

时间:2019-06-18 06:52:33

标签: node.js firebase express vue.js google-cloud-functions

我有网站的前端和后端。而且我已经在Firebase托管中部署了网站。

前端-> Vuejs,后端-> Nodejs

我的项目文件夹结构:

--client folder
     --src
         --router
         --services
               --Api.js
               --PostService.js
         --App.vue
         --database.js
         --main.js
         --store.js

 --server folder
       --dist
       --node_modules
       --app.js
       --package.json
 --.firebaserc
 --Dockerfile
 --firebase.json

在服务器端,我已经创建了用于post方法的api,以获取令牌,帐户,过期等,并传递给cardconnect付款api进行收费。

现在创建api并将付款状态的返回响应发送到前端。在本地主机上一切正常。

不知道如何为我的api创建中间件,例如 app.use()

这是我的app.js代码:

  const express = require('express')
  const bodyParser = require('body-parser')
  const cors = require('cors')
  const morgan = require('morgan')
  const firebase = require('firebase');
  const functions = require('firebase-functions');
  const admin = require('firebase-admin');

  const axios = require('axios');
  const credentials = new Buffer('testing:testing123').toString('base64')

  const app = express()
  app.use(morgan('combined'))
  app.use(bodyParser.json())
  app.use(cors())


  const  firebaseConfig = {
      apiKey: "AIzaSyDasdaddxsT1ge4WArImpRu1pIU",
      authDomain: "dev-xxx-com.firebaseapp.com",
      databaseURL: "https://dev-xxx-com.firebaseio.com",
      projectId: "dev-xxxxx-com",
      storageBucket: "dev-cxxxx-com.appspot.com",
      messagingSenderId: "8305673232323276",
      appId: "1:8303916:web:e0fd2dbb1"
    };

    const firebaseApp = admin.initializeApp(firebaseConfig);
    var db = firebaseApp.firestore();

   app.get('/gcp-scheduler', (req, res) => {
      res.send(
       [{
          title: "Hello World!",
          description: "Hi there! How are you?"
        }]
      )
    })


    // Add new post
      app.post('/list-server', (req, res) => {
      var token = req.body.token;
      var ccExp = req.body.ccExp;
      var cardNumber = req.body.cardNumber;
      var currentUserUUID = req.body.currentUserUUID;
      var amount = req.body.amount;
       console.log(token);
       console.log(ccExp);
       console.log(cardNumber);
       console.log(currentUserUUID);
       console.log(amount);

      (async() => {

      const paymentRequest = await getAuthTokenForThePayment({
    account: cardNumber,
    merchid: '496160873888',
    amount: amount, // Smallest currency unit. e.g. 100 cents to charge $1.00
    expiry: ccExp,
    currency: 'USD'
     });

  const charge = await makeCharge({
    merchid: paymentRequest.data.merchid, 
    retref: paymentRequest.data.retref
   });

   console.log(charge);
   console.log(charge.data.respstat)

   if (charge.data.respstat == 'A'){

     var data = db.collection('transactionTable').doc(charge.data.retref);

  var setAlan = data.set({
    'respstat': charge.data.respstat,
    'retref': charge.data.retref,
    'account': charge.data.account,
    'token': charge.data.token,
    'batchid': charge.data.batchid,
    'amount': charge.data.amount,
    'resptext': charge.data.resptext,
    'respcode': charge.data.respcode,
    'commcard': charge.data.commcard,
    'setlstat': charge.data.setlstat,

    });

    res.send(charge.data.respstat);


    } else if(charge.data.respstat == 'B'){

     console.log("Declined");
     res.send(charge.data.respstat);


    }else if(charge.data.respstat == 'C'){
    console.log("Retry");
    res.send(charge.data.respstat);


         }

      })();

  })

   const getAuthTokenForThePayment = async (data) => {

   try {

      const config = {
      headers: {
          'Content-Type': 'application/json',
          'Authorization': `Basic ${credentials}`
      }
   };

   const URL = 'https://fts.cardconnect.com:6443/cardconnect/rest/auth';

   return await axios.put(URL, data, config);

   } catch (error) {

     throw (error);

      }
    }

   const makeCharge = async (data) => {

    try {

      const config = {
      headers: {
          'Content-Type': 'application/json',
          'Authorization': `Basic ${credentials}`
        }
    };

    const URL = 'https://fts.cardconnect.com:6443/cardconnect/rest/capture';

    return await axios.put(URL, data, config);

     } catch (error) {

    throw (error);

      }
    }


   // app.listen(process.env.PORT || 8081)

   exports.app = functions.https.onRequest(app);

服务器-> package.json

 {
  "name": "websiteName",
  "version": "1.0.0",
  "description": "",
   "main": "app.js",
    "scripts": {
    "dev": "./node_modules/nodemon/bin/nodemon.js app.js",
    "start": "node app.js"

    },
   "author": "",
    "license": "ISC",
    "dependencies": {
    "axios": "^0.19.0",
     "body-parser": "^1.19.0",
     "cors": "^2.8.5",
     "express": "^4.17.1",
     "firebase": "^6.1.0",
     "firebase-admin": "^8.0.0",
     "firebase-functions": "^2.3.1",
     "mongoose": "^5.5.12",
     "morgan": "^1.9.1",
     "nodemon": "^1.19.1"
      }
    }

客户端->服务-> Api.js

     import axios from 'axios'
     export default() => {
        return axios.create({
        baseURL: `https://dev-xxxx-com.firebaseapp.com`
         // https://dev-xxxxx-com.firebaseapp.com/
         // http://localhost:8081
        })
      }

客户端->服务-> PostsService.js

   import Api from '@/services/Api'

   export default {
        fetchPosts () {
            return Api().get('gcp-scheduler')
        },

        addPost (params) {
             return Api().post('list-server', params)
        }

     }

Firebase.json:

 {
  "functions:": {
  "source": "./server"
 },
 "hosting": {
  "public": "./server/dist",
  "rewrites": [
    {
    "source": "**",
    "destination": "/index.html"
     },
   { "source": "**", "function": "app"}

  ],
 "ignore": [
  "firebase.json",
  "**/.*",
  "**/node_modules/**"
  ],
 "headers": [ {
  "source": "**/*.@(eot|otf|ttf|ttc|woff|font.css)",

  "headers": [ {
    "key": "Access-Control-Allow-Origin",
    "value": "*"
  } ]
  }, {
  "source": "**/*.@(jpg|jpeg|gif|png)",
  "headers": [ {
    "key": "Cache-Control",
    "value": "max-age=7200"
  } ]
   }, {
    "source": "404.html",
    "headers": [ {
    "key": "Cache-Control",
    "value": "max-age=300"
     } ]
   } ],

     "cleanUrls": true
   }

 }

当我使用yarn build in terminal时,它在服务器端创建dist文件夹,然后我使用firebase命令部署来托管vuejs / nodejs代码。结果未调用nodejs代码。不知道我犯了什么错误?如何为API编写app.use()中间件,以及如何在相同的Firebase域名(例如dev-xxx-com.firebaseapp-com)中托管vuejs / nodejs。

任何帮助都非常感谢...

0 个答案:

没有答案