如何在Firebase托管中部署vuejs / nodejs应用程序?

时间:2019-06-10 08:39:31

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

我的项目结构

enter image description here

客户端部分包含vue应用程序,服务器部分包含nodejs。在客户端处理从服务器创建的api服务。在客户端文件夹内创建了api服务,以获取服务器的响应。

这是我的客户端->服务-> api.js的结构。

enter image description here

这是客户端->服务-> api.js代码:

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

客户端-> vue.config.js 配置文件。

const path = require('path')
module.exports = {
devServer: {
compress: true,
disableHostCheck: true,
},
outputDir: path.resolve(__dirname, '../server/dist'), // build all the assets inside server/dist folder
 pluginOptions: {
'style-resources-loader': {
  preProcessor: 'scss',
  patterns: [path.resolve(__dirname, './src/styles/global.scss')]
}
},
chainWebpack: config => {
if (config.plugins.has('optimize-css')) {
  config.plugins.delete('optimize-css')
  }
 }
}

这是我的firebase配置: firebase.json

{
"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
 }
}

服务器-> app.js ,我在其中为前端创建api

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())


var Post = require("./models/post");

const firebaseConfig = {
apiKey: "AIzaSyDHDKttdke4WArImpRu1pIU",
authDomain: "dev-cxxxxxy-com.firebaseapp.com",
databaseURL: "https://dev-cxxxx-com.firebaseio.com",
projectId: "dev-clxxxx-com",
storageBucket: "dev-cxxxx-com.appspot.com",
messagingSenderId: "830534343916",
appId: "1:83916:web:e0fd232ebb1"
};

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?"
   }]
  )
})
// serve dist folder

if (process.env.NODE_ENV === 'production') {
// Static folder
app.use(express.static(__dirname + '/dist'));
// Handle SPA
app.get('**', (req, res) => res.sendFile(__dirname + '/dist/index.html'));

 }

// 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);

(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);

我的问题是,当我在购物车视图中单击“结帐”按钮时,它应通过Post api将带有令牌的当前用户卡详细信息发送到服务器(app.js)。从前端接收卡详细信息后,它应调用在app.js中实现的cardconnect charge api功能。在浏览器控制台中,当前用户卡详细信息已成功接收,但是在单击结帐费用api时未调用,它显示了一些与api无关的其他信息。

但是一切都可以在localhost中运行。客户端localhost URL: http://localhost:8080 和服务器端localhost URL: http://localhost8081

我的Firebase托管网址: https://dev-xxxx.firebaseapp.com

这是我的控制台输出屏幕截图:

enter image description here

不要在Firebase vuejs / nodejs托管中出错的地方,重写路径。

在postservice.js文件中显示错误

import Api from '@/services/Api'

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


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

 }

任何帮助,不胜感激。

0 个答案:

没有答案