I have two endpoints for aurelia-api that are registered in main.js. One points to my staging server, the other points to my local development server (Kestrel).
What is the recommended way to register endpoints or set the default endpoint so that I can switch between them easily based on environments?
.plugin('aurelia-api', config => {
config
//.registerEndpoint('api', 'http://localhost:5000/api/')
.registerEndpoint('api', 'http://server:port/api/')
.setDefaultEndpoint('api');
})
The best way to configure anything based on your environment is by utilising the environments folder, that Aurelia creates when you start your app, containing a dev and a prod environment.
dev.ts :
export default {
debug: true,
testing: true,
endpoint: "http://localhost:5000/api"
}
prod.ts
export default {
debug: false,
testing: false,
endpoint: "http://server:port/api/"
}
These compile to the file environment.ts, based on whether you're running it locally or on the server.
If you inject the environment into your file, you are able to use any variable specified in it, like so:
import environment from "./environment";
export function configure(aurelia) {
aurelia.use
.plugin('aurelia-api', config => {
config
.registerEndpoint('api', environment.endpoint)
.setDefaultEndpoint('api');
})
Related
I made an Svelte Kit its working in my local with no problem but when i build it like this:
import adapter from '#sveltejs/adapter-static';
export default {
kit: {
adapter: adapter({
fallback: 'index.html',
})
}
};
And gives me 3 folders and they are: client, prerendered, server.
I'm uploading this 3 folders in my hosting and move the folder files into root folder. Everythings works with no problem BUT i have an api that sends mail. It's gives me 404? Send mail is working in localhost but not working in hosting. I can't fixed it. In manifest.json:
{
type: 'endpoint',
id: "api/sendMail",
pattern: /^\/api\/sendMail\/?$/,
names: [],
types: [],
load: () => import('./entries/endpoints/api/sendMail/_server.js')
},
The path is correct by the way.
The folders in hosting:
Photo
What can i do?
By specifying a fallback page, this means you're turning SPA mode on, so you can't use server endpoints.
From the adapter-static readme:
You can use adapter-static to create a single-page app or SPA by
specifying a fallback page.
The reason this is working local in dev:
During development, SvelteKit will still attempt to server-side render
your routes. This means accessing things that are only available in
the browser (such as the window object) will result in errors, even
though this would be valid in the output app. To align the behavior of
SvelteKit's dev mode with your SPA, you can add export const ssr =
false to your root +layout.
I use Vue 2 with Common.js to generate an AMD Bundle. I need to be able to automatically register my service worker on runtime. Something that works:
https://www.npmjs.com/package/worker-plugin
https://www.npmjs.com/package/worker-loader
The reason I need a service worker is for sending notifications. However, I am having trouble with this, as it seems that the only workers supported are in DedicatedWorkerGlobalScope or SharedWorkers. In order to dispatch "showNotification" however, I need the Service Worker type.
So basically what I do:
import Worker from "worker-loader!./Worker.js"
const worker = new Worker()
Works like charm, as does this (Worker Plugin):
const worker = new Worker('./worker.js', { type: 'module' });
However, always normal workers. Those arent service workers and I have been trying to figure this out since hours. Is there a configuration im missing to change the type? Some insight would be great.
To illustrate what im trying to achieve:
Registration of the Service Worker needs to happen automatically on Runtime, without me having to reference absolute or relative urls.
Any insight on how I can achieve what im trying to accomplish?
I did not use your plugins but I used workbox plugin for Vue. The configuration is quite simple and well documented.
Installing in an Already Created Project
vue add workbox-pwa
Config example
// Inside vue.config.js
module.exports = {
// ...other vue-cli plugin options...
pwa: {
name: 'My App',
themeColor: '#4DBA87',
msTileColor: '#000000',
appleMobileWebAppCapable: 'yes',
appleMobileWebAppStatusBarStyle: 'black',
manifestOptions: {
start_url: '/'
},
// configure the workbox plugin
workboxPluginMode: 'GenerateSW', // 'GenerateSW' will lead to a new service worker file being created each time you rebuild your web app.
workboxOptions: {
swDest: 'service-worker.js'
}
}
}
You could use service-worker-loader instead (which is based on worker-loader).
Install service-worker-loader:
npm i -D service-worker-loader
Create a service worker script (e.g., at ./src/sw.js) with the following example contents:
import { format } from 'date-fns'
self.addEventListener('install', () => {
console.log('Service worker installed', format(new Date(), `'Today is a' eeee`))
})
Import the service worker script in your entry file:
// main.js
import registerServiceWorker from 'service-worker-loader!./sw'
registerServiceWorker({ scope: '/' }).then(registration => {
//...
registration.showNotification('Notification Title', {
body: 'Hello world!',
})
})
demo
following https://nuxtjs.org/api/configuration-env
I have been trying to set up my apiUrl in nuxt.config.js once for the whole project, like:
export default {
env: {
apiUrl: process.env.MY_REMOTE_CMS_API_URL || 'http://localhost:1337'
}
}
adding this in nuxt.config.js, I'd expect (and would like) to have apiUrl accessible everywhere in the project.
In particular, it is needed for the 3 following cases:
with axios, to generate static pages from dynamic urls (in nuxt.config.js)
generate: {
routes: function () {
return axios.get(apiUrl + '/posts')
.then((res) => {
return res.data.filter(page => {
return page.publish === true;
}).map(page => {
return {
route: '/news/' + page.slug
}
})
})
}
},
with apollo, to get data via graphql (in nuxt.config.js)
apollo: {
clientConfigs: {
default: {
httpEndpoint: apiUrl + '/graphql'
}
}
},
in every layout, page and components, as the base url of media:
<img :src="apiUrl + item.image.url" />
As you might see, only thing I need is to 'print' the actual base url of the cms.
I have also tried to access it with process.env.apiUrl, with no success.
The only way I was able to make it has been to create an extra plugin/apiUrl.js file, which injects the api url, and seems wrong to me as I am now setting the apiUrl twice in my project.
I asked this question in the past, but in a way less clear way. I was suggested to use dotenv, but from the docs it looks like adding an additional layer of complication that might not be necessary for a simpler setup.
Thanks.
I think dotenv module really is what you need.
This is my setup:
Project root has a .env file that contains
BASE_URL=https://www.myapi.com
require('dotenv').config() at top of nuxt.config.js
#nuxtjs/dotenv installed and added to buildModules of nuxt.config.js
env: { BASE_URL: process.env.BASE_URL} added to nuxt.config.js
axios: { baseURL: process.env.BASE_URL } added to nuxt.config.js (optional)
You should have access to your .env throughout the project. (process.env.BASE_URL)
I haven't used apollo, but you should be able to set the apollo endpoint with process.env.BASE_URL + '/graphql'
As of Nuxt 2.13, #nuxtjs/dotenv is not required anymore. Read here
The concept that I was missing is that you set up the same named variable in your server / pipeline, so that you have your (always local / never pushed) .env file and a same name variable remotely, not added to your repo (where the value can be the same or different)
Intro
Most of you will probably ask "Why?", why am I doing this stack? The reason is that initially I created the project in Nuxtjs + expressjs. But my PM wanted me to not distribute my source code to our client so I decided to bundle my code up into a single .exe file with electron. I tried using pkg but I couldn't figure out how to compile everything exactly.
The problem
The problem I am having with socket.io-client is that I want to be able to move the exe file to a different machine, and have socket.io connect to the socket.io server on that machine dynamically. Changing machines would mean that the IP of the server will be different, so whenever the user opens the webpage for that server, the socket.io-client would connect to the proper server. It works when I build the app from my current machine but when moved to lets say a VM then this is the response I get when I access the page:
ServiceUnavailableError: Response timeout
at IncomingMessage.<anonymous> (C:\Users\LIANG-~1\AppData\Local\Temp\nscAD47.tmp\app\resources\app.asar\node_modules\connect-timeout\index.js:84:8)
at IncomingMessage.emit (events.js:182:13)
at IncomingMessage.EventEmitter.emit (domain.js:442:20)
at Timeout._onTimeout (C:\Users\LIANG-~1\AppData\Local\Temp\nscAD47.tmp\app\resources\app.asar\node_modules\connect-timeout\index.js:49:11)
at ontimeout (timers.js:425:11)
at tryOnTimeout (timers.js:289:5)
at listOnTimeout (timers.js:252:5)
at Timer.processTimers (timers.js:212:10)
To further elaborate on what I am trying to do, lets say I compile the code on my current machine with the private IP of 192.168.0.104 (this runs perfectly), I want to move the exe file to another machine with the private IP of 192.168.0.105 (Accessing the webpage from this server gives the above error).
Technology used
The technology that I am using is nuxt.js created with express template, socket.io, and vue-socket.io-extended.
What I have tried
I have tried checking for reconnect events or timeout events, when these events are triggered then I call socket.connect(process.env.WS_URL) which doesn't work. I believe that when I packaged the electron app, it makes the plugin data immutable. I couldn't figure out someway to change the URL to the address of the machine.
import Vue from 'vue'
import io from 'socket.io-client'
import VueSocketIO from 'vue-socket.io-extended'
export default ({ store }) => {
// process.env.WS_URL = 'http://192.168.0.12:3000'
const socket = io(process.env.WS_URL, { transports: 'websocket' })
socket.on('timeout', () => {
socket.connect(process.env.WS_URL)
})
Vue.use(VueSocketIO, io(process.env.WS_URL, { transports: 'websocket' }), { store })
}
What I have right now
I created a socket.io plugin for nuxtjs to implement into my app, the plugin looks like this:
import Vue from 'vue'
import io from 'socket.io-client'
import VueSocketIO from 'vue-socket.io-extended'
export default ({ store }) => {
// process.env.WS_URL = 'http://192.168.0.12:3000'
Vue.use(VueSocketIO, io(process.env.WS_URL, { transports: 'websocket' }), { store })
}
I expect the socket.io-client to connect to the correct private IP of where the exe file is located. But Request Timeout is received, even though when I output the process.env.WS_URL is actually the new address.
EDIT: After further testing, seems like the socket.io plugin is fixed, after the build process. So changing the process.env.WS_URL wouldn't have any effect. Is there a way to change the URL for socket.io even after nuxtjs finished building?
(I wanted to comment this but I can't)
Anyway, are you sure you the information in the edit is true?
I use Nuxt.js with Electron and also the vue-socket.io. I use an argument for calling the executable as the socket.io address:
This is specific for electron
global.sharedObject = { socketIOAddress: process.argv[1] }
and this is my nuxt plugin file for vue-socket.io:
import Vue from 'vue'
import VueSocketIO from 'vue-socket.io'
import { remote } from 'electron'
export default ({ store }) => {
Vue.use(new VueSocketIO({
debug: true,
connection: remote.getGlobal('sharedObject').socketIOAddress
vuex: {
store,
actionPrefix: 'SOCKET_',
mutationPrefix: 'SOCKET_'
}
})
)
}
So while the code might not be exactly what you want Nuxt doesn't have to be build again for it. Maybe the environment variables didn't change right when you tried? You should try with a argument as well perhaps.
Also important: ssr: false in the nuxt config for the vue-socket.io plugin.
The solution I came up with is by using an environmental variable. First have the variable set as localhost:3000 or whatever your server's local address is. I would use electron-store to keep a config.json file of all my settings including the server IP. Before my server starts up, I read the config file and change the server address set previously. Then I use it as follows:
import Vue from 'vue'
import io from 'socket.io-client'
import VueSocketIO from 'vue-socket.io-extended'
export default ({ app, store }) => {
Vue.use(VueSocketIO, io(app.$env.WS_URL), { store })
}
NOTE: WS_URL is the environmental variable name.
I have a project which configures a Hapi web server via glue and compose.
Excerpt from TypeScript file:
import { compose as glue } from 'glue';
import { Store } from 'confidence';
import config from './config.json';
const manifest = new Store(config).get('/', {
env: process.env.NODE_ENV,
});
const options = {
relativeTo: __dirname,
};
const server = await glue(manifest, options);
The problem now is that all passwords are directly stored in the config.json file.
Does confidence support the injection of passwords, for example from environment variables?
Or do I somehow have to inject them afterwards, for example using nconf?
I thought same and added my small modification to manifest file. You can use external config library. I am using node-config.
Now I can separate my development and production passwords/keys/secrets.
To .gitignore file I added
config/development.json
config/test.json
config/production.json
Local development uses development.json and production uses production.json. This way I don't need to put my secrets to a file and push to the repo.
Here you can find implementation details. It will give you an idea of how this works.