I'm creating a angular app that talks to a node backend express application and using a config file to set env variables in my node app I can access my config file like this:
index.js
var port = config.get("server:port");
var server = app.listen(port, function() {});
My config file looks like this:
app.config.js
module.exports =
{
"server":{
"host":"localhost",
"port":3000
},
"mongodb": "",
"redis": {
"loadBalancerInstance": {
"host": "server",
"port": {
"default": "6379"
}
}
},
"elastic": {
"server": "server",
"port": "9200",
"user":"foo",
"password":"bar"
},
"log": {
"level": "info",
"filename": "",
"console": true,
"logio": {
"port": "28777",
"node_name": "this-server-name",
"host": "server"
}
}
};
I have statically defined the route/port to a backend
datafactory.js
angular.module('dashboard.factories')
.factory('DataFactory', function($http, $q, FormatFactory) {
var backend = function(apiEndPoint, clientKey) {
clientKey = clientKey || "";
var deferred = $q.defer();
$http.get("http://localhost:3000/<-(pull this from config file)" + apiEndPoint + "/" + clientKey)
My question is how can I access app.config.js within angular and dynamically set host/port within my angular service
I suppose if you're stuck on using the same configuration file that your node server uses, you'll have to make the .js file available to a GET request from your app, which you'll then have to parse out the string into JSON.
Edit:
You're going to have to have two configuration files, one available to your node server, and one for your angular app. Now, if you want the source to be one file, you could build that into your build process - if you use something like gulp or grunt, this would be reasonably easy. It could take the singular config file and build two files - the node server config file, and an angular module (I would suggest a constant or value) that you could inject into your data services.
If you're serving the config file at localhost:3000/config, you can do this:
angular.module('dashboard.factories')
.factory('DataFactory', function($http, $q, FormatFactory) {
$http.get('localhost:3000/config')
.success(function(config) {
$http.get(config.server.host + ":" + config.server.port)
// whatever you want here
});
});
Related
We have blog in a NuxtJs project deployed using docker and traefik's PathPrefix('/blog') so instead of being served from https://example.com/ is served from
https://example.com/blog/
version: "3.9"
services:
{{ project_id }}-awesome-blog-{{ awesome_blog_env }}:
# etc..
labels:
- traefik.http.routers.awesome_blog-{{ awesome_blog_env }}-router.rule=Host(`{{ awesome_blog_host_dns }}`) && PathPrefix(`/blog`)
# etc..
- {{ docker_network }}
networks:
{{ docker_network }}:
external: true
The issue is that because of the PathPrefix Nuxt does not seem to know the actual page. As it's receiving /blog/ as path it doesn't match any expected route
this is what this.$router prints out in the server on the server from https://example.com/blog/
{
"name": null,
"meta": {},
"path": "/blog/",
"hash": "",
"query": {},
"params": {},
"fullPath": "/blog/",
"matched": []
}
And this is what it prints in local from http://localhost.com:3000/
{
"name": "index___en",
"meta": {},
"path": "/",
"hash": "",
"query": {},
"params": {},
"fullPath": "/",
"matched": [{
//...etc
name: "index___en",
// ..etc
}]
}
I tried using the
router: {
base: '/blog/
}
Which in local works but in the server seems not to work (doesn't even get to the nuxt site and printing the server 404)
As an "ugly" alternative I tried copying all the pages inside the /blog/ folder and they do respond but my serverMiddleware does not (returns 404)
this serverMiddleware is setup like this:
nuxt.config.js
serverMiddleware: ['~/server-middleware/index.js'],
server-middleware/index.js
const nocache = require('nocache');
const express = require('express')
const buildRouter = require('../server/router.js')
const app = express()
app.use(express.json())
app.use(nocache());
buildRouter(app)
module.exports = app
server/router.js
module.exports = function (app) {
const buildApiRoute = require('./controllers/api')
buildApiRoute(app, '/api')
}
Tried with /blog/api, too
module.exports = function (app) {
const buildApiRoute = require('./controllers/api')
buildApiRoute(app, '/blog/api')
}
Anyways, is there any way to tell nuxt to ignore the /blog/ slug of the url o something similar?
Magic code
// Before anything
this.$router.fullPath = this.$router.fullpath.replace('/blog', '/')
this.$router.path = this.$router.path.replace('/blog', '/')
I want to unit test a mixin.
So I need to create a loopback 3.x application completely in code.
It works so far and it registers my mixin, but it doesn't register my model.
It is not exposed over REST, but thats exactly what I need.
Here is my code:
// create loopback app
app = loopback();
app.use(loopback.rest());
// create data source
app.dataSource('db', {
name: 'db',
connector: loopback.Memory
});
app.loopback.modelBuilder.mixins.define('accesscheck', AccessCheck);
app.loopback.createModel({
name: 'AccesscheckTest',
plural: 'AccesscheckTests',
base: "PersistedModel",
accesscheck: [{
permission: "ALLOW",
roles: [
'admin'
],
accessScope: "organization",
method: "findById"
}],
mixins: [
"accesscheck"
]
});
var Accesscheck = app.loopback.getModel('Accesscheck');
app.model(Accesscheck, { dataSource: 'db', public: true });
// start server
var connection = app.listen(3000, () => {
if (done) {
done();
}
});
app.activeConnection = connection;
return app;
PS: I know that there is the ACL Model in loopback but it doesn't fit my need so I need to implement my own Accesscheck.
You need to call boot from loopback-boot.
I think it's better to require the server.js in test units.
And make config file for test in this pattern datasources.test.json and a script in package.json for test like this : "test": "NODE_ENV=test ./node_modules/mocha/bin/mocha --recursive",
So there is no need to create models in unit tests anymore.
Hi Iam trying to set firefox profile name in environment settings of intern config file.I have tried
environments: [
{ browserName: 'firefox',firefox_profile:'default' },
{firefox_profile:'default'}
],
and
environments: [
{ browserName: 'firefox',profile:'default' },
{profile:'default'}
],
as well as
capabilities: {
'selenium-version': '2.42.0',
firefox_profile:'default'
},
as mentioned in Selenium capabilities
But still firefox launches with an anonymous profile.
However if I use watir,
def setup
#browser = Watir::Browser.new :firefox, :profile => 'default'
goto_ecp_console_manage_page
end
browser launches the default profile which is 'kinit-ed'(kerberos)
As the Selenium capabilities page you mention points out, the value of firefox_profile must be a Base64-encoded profile. Specifically, you ZIP up a Firefox profile directory, Base64 encode it, and use that string as the value of firefox_profile. The firefox-profile npm package can make this process easier. You'll end up with something like:
environments: [
{ browserName: 'firefox', firefox_profile: 'UEsDBBQACAAIACynEk...'; },
...
],
I would recommend storing the profile string in a separate module since it's going to be around 250kb.
I used #jason0x43 suggestion to rely on the firefox-profile Node.js module and I've created the following grunt task fireforProfile4selenium. With a simple configuration set into the Gruntfile.js, the plugin writes a file on disk with the Base64 encoded version of a zipped profile!
Here is the grunt configuration:
firefoxProfile4selenium: {
options: {
proxy: {
host: '...',
port: ...
},
bypass: [ 'localhost', '127.0.0.1', '...' ]
},
default: {
files: [{
dest: 'firefoxProfile.b64.txt'
}]
}
}
Here is the plugin:
/*global require, module*/
var fs = require('fs'),
FirefoxProfile = require('firefox-profile'),
taskName = 'firefoxProfile4selenium';
module.exports = function (grunt) {
'use strict';
grunt.registerMultiTask(taskName, 'Prepares a Firefox profile for Selenium', function () {
var done = this.async(),
firefoxProfile = new FirefoxProfile(),
options = this.options(),
host = this.options().proxy.host,
port = this.options().proxy.host,
bypass = this.options().bypass,
dest = this.files[0].dest;
// Set the configuration type for considering the custom settings
firefoxProfile.setPreference('network.proxy.type', 2);
// Set the proxy host
firefoxProfile.setPreference('network.proxy.ftp', host);
firefoxProfile.setPreference('network.proxy.http', host);
firefoxProfile.setPreference('network.proxy.socks', host);
firefoxProfile.setPreference('network.proxy.ssl', host);
// Set the proxy port
firefoxProfile.setPreference('network.proxy.ftp_port', port);
firefoxProfile.setPreference('network.proxy.http_port', port);
firefoxProfile.setPreference('network.proxy.socks_port', port);
firefoxProfile.setPreference('network.proxy.ssl_port', port);
// Set the list of hosts that should bypass the proxy
firefoxProfile.setPreference('network.proxy.no_proxies_on', bypass.join(','));
firefoxProfile.encoded(function (zippedProfile) {
fs.writeFile(dest, zippedProfile, function (error) {
done(error); // FYI, done(null) reports a success, otherwise it's a failure
});
});
});
};
I have been experimenting with gulp lately, and have had a lot of success, but now I am stumped.
I have gulp building everything, and I want to upload a folder afterwards. I have created a deploy task for this using gulp-scp2:
gulp.task('deploy', ['clean', 'build'], function() {
var privateKeyPath = getUserHome() + '/.ssh/id_rsa';
gulp.src('public/dist')
.pipe(scp({
host: 'myhost',
username: 'user',
dest: '/home/user/test',
agent: process.env['SSH_AUTH_SOCK'],
agentForward: true,
watch: function(client) {
client.on('write', function(o) {
console.log('write %s', o.destination);
});
}
})).on('error', function(err) {
console.log(err);
});
});
Unfortunately, when I do this, I get the following error:
Error: Content should be buffer or file descriptor
How can I copy a folder over SSH using gulp?
I did end up finding a solution by leveraging the node scp2 library:
scpClient = require('scp2');
gulp.task('scp', [], function (cb) {
scpClient.scp('local_folder', {
"host": "remote_host",
"port": "remote_port",
"username": "username_on_remote",
"path": "/path/on/remote",
"agent": process.env["SSH_AUTH_SOCK"],
"agentForward": true
}, cb)
});
As the previous answer, i ended using a node version directly, this one will work in gulp 4+ way:
First install the lib (Be sure of installing locally in the project, the global version doesnt work for using in gulp file):
npm install scp2
Then in the gulp file:
var scpClient = require('scp2');
function deploySCP2(){
return scpClient.scp(paths.buildAll, {
"host": "host",
"username": "username",
"password": "password",
"path": "path"
}, function(err) { })
}
This will work rightaway.
I have a node.js application where I am using Winston to track some logging. I want to have a server side log in addition to the client side. In the express framework is it just the files in the public folder that are accessible to the client and if I want to do a server side log where the client users can not access it can I create a folder outside of public?
Exactly, just point the log file to be outside the /public folder and whatever other folders you have configured in app.use(express.static(path.join(__dirname, 'public_folder')));
You can configure were the winston tranports will log the files by setting its proper attributes, for instance, in the file transport you have to set the filename option.
The following is a config.js file from I load all configuration for my logging activities (server side and client requests):
config.json
{
"transports": {
"console": {
"enabled": true,
"colorize" : true,
"timestamp": false
},
"file" : {
"enabled": true,
"colorize" : true,
"filename" : "/var/log/vifros.log",
"timestamp": true
},
"mongodb": {
"enabled": true,
"db": "vifros"
}
}
}
EDIT LOGGING- logger.js -- (see comment):
var winston = require('winston');
require('winston-mongodb').MongoDB; // Monkeypatch Winston for MongoDb transport.
var config = require('../config');
/*
* Enable initially all transports for initial app startup and then disable them according to settings.
*
* Add console transport.
*/
winston.remove(winston.transports.Console); // To being able to reconfigure it.
if (config.logging.transports.console.enabled) {
winston.add(winston.transports.Console, config.logging.transports.console);
}
/*
* File transport.
*/
if (config.logging.transports.file.enabled) {
winston.add(winston.transports.File, config.logging.transports.file);
}
/*
* Enable saving logs to mongodb.
*/
if (config.logging.transports.mongodb.enabled) {
winston.add(winston.transports.MongoDB, config.logging.transports.mongodb);
}
exports.logger = winston;
exports.tags = {
init : 'init',
api_request: 'api_request',
db : 'db',
validation : 'validation',
cross_rel : 'cross_relationship',
os : 'os'
};