When I finish to deploy my vapor app to Heroku. But my app didn't actually work on the url I made in Heroku. The url is worked, but the action couldn't be take. I think my DATABASE_URL cannot be configured.And I don't know how to fix this. If there is something I need to add please tell me.
import Vapor
import Fluent
import FluentPostgresDriver
import FluentPostGIS
import Vapor
extension Environment {
static var databaseURL: URL {
guard let urlString = Environment.get("DATABASE_URL"), let url = URL(string: urlString) else {
fatalError("DATABASE_URL not configured")
}
return url
}
}
// configures your application
public func configure(_ app: Application) throws {
// uncomment to serve files from /Public folder
// app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
app.migrations.add(CreateUser())
app.migrations.add(CreateInfo())
app.migrations.add(CreateUserToken())
app.sessions.use(.fluent)
app.databases.use(.postgres(hostname: "localhost", username: "postgres", password: "", database: "template1"), as: .psql)
try routes(app)
}
For your reference: https://github.com/mobile-dev-enginner/TILAPP
Command: heroku login -> heroku config
Related
So Laravel decided to innovate once again and fix what was not broken, so Mix is gone and now default asset bundling goes with Vite.
I'm following the absolute default in their documentation to a bunch of front-end bugs and finally only several remained:
I use Laragon with SSL.
I haven't configured anything additional and my vite.config.js looks like this:
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '#vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
});
When I run npm run dev and visit the Laragon domain I get the following in the console:
client.ts:78 WebSocket connection to 'wss://127.0.0.1:5173/' failed.
client.ts:48 [vite] failed to connect to websocket.
your current setup:
(browser) 127.0.0.1:5173/ <--[HTTP]--> 127.0.0.1:5173/ (server)
(browser) 127.0.0.1:5173/ <--[WebSocket (failing)]--> 127.0.0.1:5173/ (server)
Check out your Vite / network configuration and https://vitejs.dev/config/server-options.html#server-hmr .
I guess I need to configure my actual domain somewhere? I tried doing that in a server object in the config, but it didn't help those errors.
PS: Now in my vue files I need to import including the .vue extension e.g. import Button from '#/Components/Button.vue' is there any way I can ommit the .vue like it was with Laravel Mix?
I haven't use laragon before, but if you have a custom domain, eg, like
http://cutom-domain.test, you need to tell vite to use the certificate like so;
In your vite.config.js, add a server key with the following configuration
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '#vitejs/plugin-vue';
import fs from 'fs';
import { homedir } from 'os';
import { resolve } from 'path';
// Ignore the protocol on the host, ie do not put "http"
const host = 'cutom-domain.test';
const viteServerConfig = host => {
let keyPath = resolve(homedir(), `.config/valet/Certificates/${host}.key`)
let certificatePath = resolve(homedir(), `.config/valet/Certificates/${host}.crt`)
if (!fs.existsSync(keyPath)) {
return {}
}
if (!fs.existsSync(certificatePath)) {
return {}
}
return {
hmr: {host},
host,
https: {
key: fs.readFileSync(keyPath),
cert: fs.readFileSync(certificatePath),
},
}
}
export default defineConfig({
server: viteServerConfig(host),
plugins: [
laravel({
input: 'resources/js/app.js',
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
});
Credit to this blogpost that explains more - Making Vite and Valet play nice together
I don't know if it's still relevant, but looking in the source code of laravel-vite-plugin I found a way to solve this problem in a very simple way, without even changing the vite.config.js file.
Put these two variables in the .env file and set them with full path to .key and .crt files on your system:
VITE_DEV_SERVER_KEY='C:/laragon/etc/ssl/laragon.key'
VITE_DEV_SERVER_CERT='C:/laragon/etc/ssl/laragon.crt'
Do not change anything on vite.config.js file. Here is my (fresh install of laravel + jetstream w/ inertia and --ssr):
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '#vitejs/plugin-vue';
export default defineConfig({
plugins: [
laravel({
input: 'resources/js/app.js',
ssr: 'resources/js/ssr.js',
refresh: true,
}),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
});
And that's it. Run npm run dev and Vite will "magically" start a development server with https on.
VITE v4.0.4 ready in 1248 ms
➜ Local: https://laravel.test:5173/
➜ Network: https://192.168.1.2:5173/
➜ press h to show help
LARAVEL v9.48.0 plugin v0.7.3
➜ APP_URL: https://laravel.test/
Even though the configuration present in the official documentation also works, this way is much simpler, and the host, key and cert variables are not defined in the file, but they are dynamic reflecting the dev environment.
Hope this helps someone.
Here is the source where I found this, and you can also inspect in node_modules\laravel-vite-plugin\dist\index.js of your project.
When I do npm run build instead of regular npm run dev, the problem is gone. I guess, build mechanism is different for prod, so there is no WSS related errors in console.
So, in other words, perform a production Vite build and deploy it (if you are testing on a remote project).
I'm currently really frustating cause cannot deploy my app to Heroku and connect my db to Google Cloud SQL.
What am I already did?
I have been set up SSL to connect them
I have been set up Cloud SQL Auth Proxy (+ set up Cloud SQL CLient role in IAM Manager)
I have been did buildpacks via Heroku approaches
etc.
And overall failed.
This is my config database via Typeorm in Nestjs.
import { TypeOrmModuleOptions } from "#nestjs/typeorm"
const fs = require("fs");
require('dotenv').config()
export class OrmConfig {
// Config TypeOrm
getConfig() {
const ormConfig: TypeOrmModuleOptions = {
type: 'postgres',
url: 'postgres://myusername:mypassword#myhostincloudsql(publicip):5432/mydb',
// host: 'myhostincloudsql(public ip)',
// port: 5432,
// username: 'myusername',
// password: 'mypassword',
// database: 'mydb',
entities: ['dist/**/*.entity{.js,.ts}'],
synchronize: false,
migrationsRun: true,
logging: false,
logger: 'file',
migrations: [
'dist/database/migrations/**/*{.js, .ts}'
],
cli: {
migrationsDir: 'database/migrations'
},
ssl: true,
extra: {
ssl: {
ca: fs.readFileSync('./src/config/server-ca.pem'),
cert: fs.readFileSync('./src/config/client-cert.pem'),
key: fs.readFileSync('./src/config/client-key.pem'),
// rejectUnauthorized: false
}
}
}
return ormConfig
}
}
export default new OrmConfig().getConfig()
This is my app.module.ts
import { SendGridModule } from '#anchan828/nest-sendgrid';
import { MiddlewareConsumer, Module, NestModule } from '#nestjs/common';
import { ConfigModule } from '#nestjs/config';
import { TypeOrmModule } from '#nestjs/typeorm';
// import { BlogModule } from './blog/blog.module';
import OrmConfig from './config/ormConfig';
import { BusinessContactModule } from './contact/business/business.module';
import { InvestorNotificationController } from './contact/investor/investment-recommendation/investor-notification.controller';
import { InvestmentRecommendationModule } from './contact/investor/investment-recommendation/investor-notification.module';
import { InvestorContactModule } from './contact/investor/angel-investor/investor.module';
import { EmitenCampaignModule } from './emiten-campaign/emiten-campaign.module';
import { EmitenModule } from './emiten/emiten.module';
import { FlashMobileModule } from './flash-mobile/flash-mobile.module';
import { CoreModule } from './global/core.module';
import { Agent } from './middleware/agent';
import { AuthModule } from './middleware/auth.module';
import { TekenajaModule } from './tekenaja/tekenaja.module';
import { UserModule } from './user/user.module';
require('dotenv').config();
#Module({
imports: [
/**
* ================================
* Typeorm Config
* ================================
*/
SendGridModule.forRoot({
apikey: process.env.SENDGRID_API_KEY,
}),
TypeOrmModule.forRoot(OrmConfig), // This is I call it
ConfigModule.forRoot(),
AuthModule,
TekenajaModule,
FlashMobileModule,
CoreModule,
EmitenModule,
EmitenCampaignModule,
// InvestorContactModule,
// BusinessContactModule,
UserModule,
// BlogModule
InvestmentRecommendationModule
]
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(Agent)
.forRoutes('/');
}
}
NB: Anyway, I'm using public ip in Google Cloud SQL
I have tried connect it from Heroku Postgres, and works. And I try with Cloud SQL fields, getting error something like this
Now, what should I do in order to connected between them? I hope reply my issue guys. Many thanks.
In CloudSQL - your instance must have Public IP address ( section Connection ) and you need address IP in Authorised network from where you will try connect. Ofc you can setup 0.0.0.0 but don't do it. Better way is setup ssh connection.
Try running the Cloud SQL Proxy in addition to your app in the same dynamo.
For example:
web: trap '' SIGTERM; ./cloud_sql_proxy -credential_file sa.json -instances=INSTANCE_CONN_NAME=tcp:5432 & npm start & wait -n; kill -SIGTERM -$$; wait
Note, you'll need to ensure the Cloud SQL Proxy binary and a credential file is included with your app. And you won't want to check those into source control.
See https://help.heroku.com/CTFS2TJK/how-do-i-run-multiple-processes-on-a-dyno.
I have solved my issue. As mentioned #Sebastian Pietrzak, I should implemented 0.0.0.0/0 in Authorized Network in the Connection Menu. And for the additional you have to set the SSL appoach.
Many thanks everyones
I am trying to deploy my NestJS REST API on Heroku but I always get the following error:
Web process failed to bind to $PORT within 60 seconds of launch
My configuration is pretty straight forward:
In my main.ts I start my server with:
await app.listen(process.env.PORT || AppModule.port);
I added a Procfile in the root directory of my project which contains:
web: npm run start:prod
My package.json files contains these scripts:
"build": "tsc -p tsconfig.build.json",
"prestart:prod": "rimraf dist && npm run build",
"start:prod": "node dist/main.js",
The process on Heroku builds succesfully, prints out these seamingly reassuring lines:
TypeOrmModule dependencies initialized
SharedModule dependencies initialized
AppModule dependencies initialized
But then immediately crashes with:
Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
I use .env configuration across my application but I removed all HOST and PORT variables (and code references), so I have no clue what could be the cause of this error.
Am I missing something?
EDIT
I am hereby sharing my app.module and main.ts files:
app.module.ts
#Module({
imports: [
SharedModule,
TypeOrmModule.forRootAsync({
imports: [SharedModule],
inject: [ConfigService],
useFactory: async (configService: ConfigService) => ({
type: 'postgres',
host: configService.getString('POSTGRES_HOST'),
port: configService.getNumber('POSTGRES_DB_PORT'),
username: configService.getString('POSTGRES_USER'),
password: configService.getString('POSTGRES_PASSWORD'),
database: configService.getString('POSTGRES_DB'),
entities: [__dirname + '/**/*.entity{.ts,.js}'],
} as PostgresConnectionOptions),
}),
UserModule,
],
controllers: [
AppController,
],
providers: [
AppService,
],
})
export class AppModule {
static port: number;
static isDev: boolean;
constructor(configurationService: ConfigService) {
console.log(process.env.PORT);
AppModule.port = configurationService.getNumber('PORT');
AppModule.isDev = configurationService.getBoolean('ISDEV');
}
}
My configuration.service.ts is a simple utility that reads from .env files:
import * as dotenv from 'dotenv';
import * as path from 'path';
#Injectable()
export class ConfigService {
constructor() {
const filePath = path.resolve('.env');
dotenv.config({
path: filePath,
});
}
getNumber(key: string): number | undefined {
return +process.env[key] as number | undefined;
}
getBoolean(key: string): boolean {
return process.env[key] === 'true';
}
getString(key: string): string | undefined {
return process.env[key];
}
}
And finally my main.ts file:
async function bootstrap() {
console.log(process.env.PORT);
const app = await NestFactory.create(AppModule);
app.enableCors();
app.useGlobalPipes(new ValidationPipe(), new TimeStampPipe());
app.use(json({ limit: '5mb' }));
app.setGlobalPrefix('api/v1');
await app.listen(process.env.PORT || AppModule.port);
}
bootstrap();
Could it be that my configuration.service.ts is interfering with heroku's env file?
If you are using fastify instead express as your platform, you need to define the host to 0.0.0.0 explicitly like this :
const port = process.env.PORT || AppModule.port;
const host = '0.0.0.0';
await app.listen(port, host);
This problem is caused by the fastify library. See the related discussion here: Fastify with Heroku.
Just as a summary, be careful on the database connection timeout that could lead to a global timeout of the heroku bootstrap as describe above
I got this working with my public github account where I was using something like this:
maven {
url "https://raw.githubusercontent.com/tvelev92/reactnativeandroidmaven/master/"
}
Then I decided I want it to be private and I put it on my company's gitlab and provisioned an access token however, I cannot figure out how to change build.gradle to accomplish a successful import of the pom file. Here is what I have however, I am receiving a 401 server response.
maven {
url "https://gitlabdev../../mobile/mysdk"
credentials(HttpHeaderCredentials) {
name = "password"
value = "..."
}
authentication {
header(HttpHeaderAuthentication)
}
}
please try:
url "https://raw.githubusercontent.com/tvelev92/reactnativeandroidmaven/raw/master/"
I'm starting to learn Vue JS and now trying to learn in nativescript-vue.
What should I do in order to have an offline DB where I can store my data without using internet connection. I heard about Firebase but I think I can't use my app if I don't have an internet connection. Thanks!
You can use Firebase with persistence enabled or you can use sqlite (https://www.npmjs.com/package/nativescript-sqlite) with vuex quite nicely.
Simple solution:
If you use applications settings within your app you can store simple data in a json object.
If you check out: https://www.nativescript.org/blog/key-value-local-storage-in-a-vue.js-nativescript-app-with-vuex
This article includes a step by step example of how to implement including using vuex store.
from that page: (store)
import Vue from 'nativescript-vue';
import Vuex from 'vuex';
import * as ApplicationSettings from "application-settings";
Vue.use(Vuex);
const store = new Vuex.Store({
state: {
firstname: "",
lastname: ""
},
mutations: {
load(state) {
if(ApplicationSettings.getString("store")) {
this.replaceState(
Object.assign(state, JSON.parse(ApplicationSettings.getString("store")))
);
}
},
save(state, data) {
state.firstname = data.firstname;
state.lastname = data.lastname;
}
}
});
Vue.prototype.$store = store;
module.exports = store;
Then save in your app with:
methods: {
save() {
this.$store.commit("save", this.input);
},
}
You will need to add a mutation to save to application settings as well:
a simple way to do that is add to the save mutation:
save(state, data) {
state.firstname = data.firstname;
state.lastname = data.lastname;
ApplicationSettings.setString("store", JSON.stringify(state));
}