【发布时间】:2021-06-21 12:31:04
【问题描述】:
我使用 Vue 制作了一个 spa,并希望将其部署在 Heroku 上并使用 Postgres 配置一个数据库。
我设法让应用程序在 Heroku 上运行,并带有一个节点服务器。我添加了数据库和连接(在同一个文件中),它正在生产中工作。 但是我想使用 Axios 向数据库发出 HTTP 请求,并在部署之前在本地进行测试。这就是我卡住的地方。
我已将 DATABASE_URL 复制到 .env 中,但仍然无法访问数据库。当我将值打印到控制台时,它始终是未定义的。
我的 server.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}`);
用户服务.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 连接到数据库。
我找遍了,但没有找到答案。
【问题讨论】:
-
请不要将代码发布为图片。详情请见此处:meta.stackoverflow.com/questions/285551
-
好的,谢谢,我会注意的。
标签: node.js postgresql heroku vuejs2 axios