如何使用Axios和Vue在heroku上的Postgres数据库



我用Vue做了一个spa,并想在Heroku上部署它,并用Postgres提供一个数据库。

我设法让应用程序在Heroku上运行,并使用节点服务器。我添加了数据库和连接(在同一个文件中(,它正在生产中工作。但我想发出HTTP请求,用Axios消除数据库,并在部署前在本地进行测试。这就是我被困的地方。

我已经将DATABASE_URL复制到了a.env中,但仍然无法访问数据库。当我将值打印到控制台时,它总是未定义的。

我的服务器.js:

const express = require("express");
const serveStatic = require("serve-static");
const path = require("path");
const port = process.env.PORT || 8080;
// Connection to the database
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: {
rejectUnauthorized: false
}
});
client.connect();
client.query('SELECT table_schema,table_name FROM information_schema.tables;', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
//
const app = express();
//here we are configuring dist to serve app files
app.use("/", serveStatic(path.join(__dirname, "/dist")));
// this * route is to serve project on different page routes except root `/`
app.get(/.*/, function (req, res) {
res.sendFile(path.join(__dirname, "/dist/index.html"));
});
app.listen(port);
console.log(`app is listening on port: ${port}`);

UserService.js:

import axios from 'axios';
// the single Axios instance we use for calls
const apiClient = axios.create({
//baseURL: 'http://localhost:5000',
baseURL: process.env.DATABASE_URL, // with ssl?
withCredentials: false, // this is the default
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
export default {
/* with pagination */
getUsers() {
console.log(process.env.DATABASE_URL);
return apiClient.get('/users');
},
};

package.json:

{
"name": "test-deploy-heroku",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"start": "node server.js"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"dns": "^0.2.2",
"express": "^4.17.1",
"pg": "^8.5.1",
"pg-native": "^3.0.0",
"vue": "^2.6.11",
"vue-router": "^3.2.0",
"vuetify": "^2.4.0",
"vuex": "^3.4.0"
},
"devDependencies": {
"@vue/cli-plugin-babel": "~4.5.0",
"@vue/cli-plugin-eslint": "~4.5.0",
"@vue/cli-plugin-router": "~4.5.0",
"@vue/cli-plugin-vuex": "~4.5.0",
"@vue/cli-service": "~4.5.0",
"@vue/eslint-config-prettier": "^6.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-prettier": "^3.3.1",
"eslint-plugin-vue": "^6.2.2",
"prettier": "^2.2.1",
"sass": "^1.32.0",
"sass-loader": "^10.0.0",
"vue-cli-plugin-vuetify": "~2.3.1",
"vue-template-compiler": "^2.6.11",
"vuetify-loader": "^1.7.0"
}
}

我将配置变量复制到本地.env文件

heroku config:get CONFIG-VAR-NAME -s  >> .env

他们开始了

heroku local

但我仍然无法使用axios连接到数据库。

我到处找,但没有找到答案。

您可能需要将require('dotenv'(.config((添加到server.js文件的顶部

if (process.env.NODE_ENV === 'development') require('dotenv').config()

最新更新