Как развернуть приложение vuejs / nodejs на хостинге Firebase? - PullRequest
0 голосов
/ 10 июня 2019

Структура моего проекта

enter image description here

клиентская часть содержит приложение vue, а серверная часть содержит nodejs.На стороне клиента обработка API-сервиса, который создается с сервера.Созданные сервисы API в папке клиента для получения ответа от сервера.

Вот моя структура client-> services-> api.js.

enter image description here

здесь 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 файл конфигурации.

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

Server-> app.js , где я создаю APIдля 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);

Моя проблема, когда я нажимаю кнопку «Оформить заказ» в представлении корзины, она должна отправить данные текущей карты пользователя с токеном на сервер (app.js) через post api.После получения информации о карте от внешнего интерфейса, она должна вызвать функциональность api обвинения cardconnect, которую я реализовал в app.js.В консоли браузера информация о текущей пользовательской карте получена успешно, но при нажатии кнопки checkout api не вызывается, она показывает некоторые другие, не связанные с api.

Но все работает в localhost.URL-адрес локального хоста на стороне клиента: http://localhost:8080 и URL-адрес локального хоста на стороне сервера: http://localhost8081.

URL-адрес моего хостинга 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)
  }

 }

Любая помощь высоко ценится пожалуйста.

...