how to deploy vuejs/nodejs app in firebase hosting

2020-05-05 17:45发布

My project structure

enter image description here

client part contains vue app and server part contains nodejs. In client side handling api service which is created from server. Created api services inside client folder to get response from server.

here is my structure of client-> services->api.js.

enter image description here

here is client -> services -> api.js code:

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

client -> vue.config.js configuration file.

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')
  }
 }
}

Here is my firebase configuration: 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
 }
}

Server-> app.js where i'm creating api for front-end

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

My issue when i click on checkout button in cart view, it should send current user card details with token to the server(app.js) through post api. After receiving card details from front-end, it should call cardconnect charge api functionality which i have implemented in app.js. In browser console current user card details received successfully but while clicking checkout charge api are not called it shows some other which is unrelated to api.

But everything works in localhost. client side localhost url: http://localhost:8080 and server side localhost url: http://localhost8081.

my firebase hosting url: https://dev-xxxx.firebaseapp.com

here is my console output screenshot:

enter image description here

Dont where i am making mistakes in firebase vuejs/nodejs hosting, rewrites path.

it show error in postservice.js file

import Api from '@/services/Api'

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


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

 }

Any help much appreciated pls..

0条回答
登录 后发表回答