Grunt Livereload + Grunt Connect Proxy - ruby-on-rails

I am using Rails for my API, AngularJS on the front and I am having some issues getting livereload / grunt connect proxy to work properly.
Here is the snippet from my gruntfile:
connect: {
options: {
port: 9000,
// Change this to '0.0.0.0' to access the server from outside.
hostname: 'localhost',
livereload: 35729
},
proxies: [
{
context: '/api',
host: 'localhost',
port: 3000
}
],
livereload: {
options: {
open: true,
base: [
'.tmp',
'<%= yeoman.app %>'
],
middleware: function (connect, options) {
var middlewares = [];
var directory = options.directory || options.base[options.base.length - 1];
// enable Angular's HTML5 mode
middlewares.push(modRewrite(['!\\.html|\\.js|\\.svg|\\.css|\\.png$ /index.html [L]']));
if (!Array.isArray(options.base)) {
options.base = [options.base];
}
options.base.forEach(function(base) {
// Serve static files.
middlewares.push(connect.static(base));
});
// Make directory browse-able.
middlewares.push(connect.directory(directory));
return middlewares;
}
}
},
test: {
options: {
port: 9001,
base: [
'.tmp',
'test',
'<%= yeoman.app %>'
]
}
},
dist: {
options: {
base: '<%= yeoman.dist %>'
}
}
}
If I 'grunt build' everything works perfectly - off localhost:3000
However if I 'grunt serve' it opens a window through 127.0.0.1:9000 and I get 404 to all my API calls.
Also under serve it is mangling my background images from a CSS file I get this warning:
Resource interpreted as Image but transferred with MIME type text/html: "http://127.0.0.1:9000/images/RBP_BG.jpg"
I haven't done this before - so chances are I am doing it all wrong.

I don't like too much code in your connect.livereload.middleware configuration.
Is that all necessary ?
Take a look at this commit - chore(yeoman-gruntfile-update): configured grunt-connect-proxy in some of my projects.
backend is Django
ports: frontend: 9000, backend: 8000
generator-angular was in v.0.6.0 when generating the project
my connect.livereload.middleware configuration was based on: https://stackoverflow.com/a/19403176/1432478

This is an old post, but please make sure that you actually initialize the proxy in the grunt serve task by calling configureProxies before livereload.
grunt.task.run([
'clean:server',
'bower-install',
'concurrent:server',
'autoprefixer',
'configureProxies',
'connect:livereload',
'watch'
]);
Should work fine afterwards.

I have a similar problem with you but I have no use yeoman.
My solution is to add the task 'configureProxies'.
this is my tasks:
grunt.registerTask('serve', ['connect:livereload','configureProxies',
'open:server', 'watch']);
and,'connect:livereload','configureProxies'——After my test, the order of these two tasks will not affect the results.
github grunt-connect-proxy

Related

Having problems to add SSL to nuxt-axios web app on DOCKER

Well after many tests and brain burns trying with nginx, caddy and other resources to apply SSL I resort to this medium.
all the services are running on docker container.
I can't fully apply the certificates, rather I can't get my site to work with SSL, I can get to the login with https but then I can't get past that barrier:
to formalize:
https://example.com:3000/login (basic web domain)
https://example.com:3001/api (all my resources)
for https i have to change the axios BASEurl form: (recomendations from caddy forum)
this: http://example.com:3001/api
to this: https://example.com/api
to stop having the error of ERR_SSL_PROTOCOL_ERROR
I share my settings from my last failed attempt with caddy.
The truth is that at this point I don't know if it is a bad configuration problem on the caddy side or on the node-nuxt-axios side.
caddyfile:
{
debug
}
example.com {
handle_path /api/* {
reverse_proxy /api/* node:3001
}
handle {
reverse_proxy node:3000
}
}
emqx.example.com {
reverse_proxy emqx:18083
}
ws.example.com {
reverse_proxy emqx:8083
}
wss.example.com {
reverse_proxy emqx:8084
}
portainer.example.com {
reverse_proxy portainer:9000
}
here it goes nuxt.config.js
axios: {
baseURL: process.env.AXIOS_BASE_URL
},
env: {
mqtt_prefix: process.env.MQTT_PREFIX,
mqtt_host: process.env.MQTT_HOST,
mqtt_port: process.env.MQTT_PORT
},
server: {
https: true,
port: 3000,
host: '0.0.0.0',
},
serverMiddleware: {
https: true,
'/api': '~/api'
},
here is the index.js for api
const express = require("express");
const mongoose = require("mongoose");
const morgan = require("morgan");
const cors = require("cors");
const colors = require("colors");
const app = express();
require("dotenv").config();
//express config
app.use(morgan("tiny"));
app.use(express.json());
app.use(express.urlencoded({
extended: true,
})
);
app.use(cors());
app.use("/api", require("./routes/devices.js"));
app.use("/api", require("./routes/users.js"));
app.use("/api", require("./routes/templates.js"));
app.use("/api", require("./routes/datas.js"));
app.use("/api", require("./routes/webhooks.js"));
app.use("/api", require("./routes/emqxapi.js"));
app.use("/api", require("./routes/alarms.js"));
app.use("/api", require("./routes/controls.js")); // nueva funcion
app.use("/api", require("./routes/dataprovider.js"));
module.exports = app;
//listener
app.listen(process.env.API_PORT, () => {
console.log("API server listening on port " + process.env.API_PORT);
}); //api port 3001
for the record all services works like a charm on http, but having problems with secure comunication.

How to use PM2 Process Manager with SvelteKit

I am trying to manage my SvelteKit build with PM2 (Process Manager) — my problem is that I can't succesfully inject a .env-file using an ecosystem.config.cjs. My files currently look like this:
.env.production
PORT=3000
The only changing thing in both configs is at:
env: { }
ecosystem.config.cjs (working fine - app runs on provided port)
module.exports = {
apps: [
{
name: 'my_app',
script: './build/index.js',
watch: false,
ignore_watch: ['database'],
autorestart: true,
// --------------------------------------------------
// if passed directly PORT is being used as expected:
// --------------------------------------------------
env: {
PORT: 3000
}
}
]
};
ecosystem.config.cjs (not working - injected PORT variable is being ignored)
module.exports = {
apps: [
{
name: 'my_app',
script: './build/index.js',
watch: false,
ignore_watch: ['database'],
autorestart: true,
// ----------------------------------------------------
// when I try to inject a .env it's just being ignored:
// ----------------------------------------------------
env: {
ENV_PATH: "./.env.production",
}
}
]
};
Any help is much appreciated and thanks for reading!
Cheers,
Boris
EDIT: Made question a bit more clear + added answer below
The problem wasn't the injection of .env.production, but the PORT environment variable. PORT must be provided directly and can't be part of .env.production (well, it can be but will be ignored).
There's probably another way, but the following works:
ecosystem.config.cjs
module.exports = {
apps: [
{
name: 'my_app',
script: './build/index.js',
watch: false,
ignore_watch: ['database'],
autorestart: true,
// ----------------------------------------------------
// when I try to inject a .env it's just being ignored:
// ----------------------------------------------------
env: {
PORT: 3000,
ENV_PATH: "./.env.production",
}
}
]
};
.env.production
# production
PUBLIC_test=value

How to pass environment variables to a front-end web application in nginx?

I am using docker-compose with an image made by someone else and I would like to use environment variables to assign it dynamically
docker-compose.yml
version: "3.7"
services:
appfronted2:
image: trafex/alpine-nginx-php7
container_name: fronted2
ports:
- "80:8080"
volumes:
- ./fronted2:/var/www/html
environment:
- HOST_BACKEND=172.99.0.11
- PORT_BACKEND=4000
networks:
tesis:
ipv4_address: 172.99.0.13
and this is my javascript where I would like to get the variables but I can't get those variables
api.js
const HOST = process.env.HOST_BACKEND || "127.0.0.1"
const PORT = process.env.PORT_BACKEND || "4000"
const URL_API = `http://${HOST}:${PORT}/api`
You are using nginx web server container to serve your html and JS files. The web server serves these files to browser as they are. This is different from using npm start where Node engine serves the HTML and JS files dynamically.
When your JS file runs on client browser, there's no variable called process.env.
Going over comments for following issue in Create React app might help you understand more:
https://github.com/facebook/create-react-app/issues/2353
If you don't have more environment variables, simplest solution would be to use window.location.hostname and prepare or select the API url accordingly.
app-config.js
let backendHost;
const hostname = window && window.location && window.location.hostname;
if(hostname === 'whatsgoodonmenu.com') {
backendHost = 'https://api.whatsgoodonmenu.com';
} else {
backendHost = 'http://localhost:8080';
}
export const API_ROOT = `${backendHost}`;
Using in component
import React from "react"
import {API_ROOT} from './app-config'
export default class UserCount extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
}
componentDidMount() {
fetch(`${API_ROOT}/count`)
.then(response => response.json())
.then(data => this.setState({ data }));
}
render(){
return(
<label>Total visits: {this.state.data}</label>
);
}
}

How to configure webpack devServer port?

I'm trying to use webpack in my Symfony app in docker, but I'm still getting error:
GET http://localhost:8000/sockjs-node/info?t=1556798329924 404 (Not Found)
Everything works fine axcepts this error...
App is running on port 8000 and node on port 8081. The address with 8081 port is accessible, but how can I tell webpack to use port 8081 with devServer?
Here is my webpack.config.js:
const Encore = require('#symfony/webpack-encore');
const StyleLintPlugin = require('stylelint-webpack-plugin');
const outputPath = './public/build/';
const publicPath = '/build';
Encore
.setOutputPath(outputPath)
.setPublicPath(publicPath)
// Clean output dir before build
.cleanupOutputBeforeBuild()
.splitEntryChunks()
.enableSingleRuntimeChunk()
// uncomment if you're having problems with a jQuery plugin
.autoProvidejQuery()
// Generate JS files
.addEntry('loader', './assets/javascript/loader.js')
.addEntry('admin-loader', './assets/javascript/admin.js')
// Generate CSS files
.addStyleEntry('forms', './assets/styles/forms.scss')
.addStyleEntry('grid', './assets/styles/grid.scss')
.addStyleEntry('reboot', './assets/styles/reboot.scss')
.addStyleEntry('styles', './assets/styles/styles.scss')
.addStyleEntry('utilities', './assets/styles/utilities.scss')
.addStyleEntry('admin', './assets/styles/admin.scss')
.enableEslintLoader()
.configureTerserPlugin((options) => {
options.cache = true;
options.parallel = true;
options.terserOptions = {
output: {
comments: false,
}
}
})
.configureSplitChunks((options) => {
options.chunks = 'all',
options.maxInitialRequests = Infinity,
options.cacheGroups = {
vendor: {
test: /[\\/]node_modules[\\/]/,
name(module) {
const packageName = module.context.match(/[\\/]node_modules[\\/](.*?)([\\/]|$)/)[1];
return `pckg.${packageName.replace('#', '')}`;
},
}
}
})
// Enable SASS loader with PostCSS config
.enableSassLoader()
.enablePostCssLoader()
.enableSourceMaps(!Encore.isProduction())
.enableVersioning(Encore.isProduction())
// CSS Hot Loader for HMR in webpack dev server
.addLoader({
enforce: 'post',
test: /\.(s?c|sa)ss$/,
exclude: /node_modules/,
loader: 'css-hot-loader',
})
.addPlugin(new StyleLintPlugin({
lintDirtyModulesOnly: Encore.isProduction(),
context: './assets/styles/',
quiet: false,
}));
const config = Encore.getWebpackConfig();
// Export settings and generate files
module.exports = config;
Does anyone know?

Disable LiveReload with Yeoman

When testing in IE8, LiveReload throws errors since web sockets is not supported. Is there a way to configure yeoman to disable LiveReload?
IE8 isn't supported by Yeoman, for good reason.
However, you could do what Allan describes, or you could override the server task, by putting this in your Gruntfile:
grunt.registerTask('server', 'yeoman-server');
Try to use <!--[if !IE]><!--></body><!--<![endif]--><!--[if IE]></body><!--<![endif]--> instead of </body>.
Generator would try to replace first </body> element and add livereload snippet before it, so code would be placed in invisible for IE space.
P.S. It`s dirty hack so use this carefuly
Put this in your Gruntfile:
grunt.registerHelper('reload:inject', function () {
return function inject(req, res, next) {
return next();
}});
Yes there is one I know.
Go to your project folder and find the file Gruntfile.js
Open the file in a editor
Remove the reload: in watch:
It will look something like this:
// default watch configuration
watch: {
coffee: {
files: 'app/scripts/**/*.coffee',
tasks: 'coffee reload'
},
compass: {
files: [
'app/styles/**/*.{scss,sass}'
],
tasks: 'compass reload'
},
reload: {
files: [
'app/*.html',
'app/styles/**/*.css',
'app/scripts/**/*.js',
'app/images/**/*'
],
tasks: 'reload'
}
}
And after you have removed it something like this:
// default watch configuration
watch: {
coffee: {
files: 'app/scripts/**/*.coffee',
tasks: 'coffee reload'
},
compass: {
files: [
'app/styles/**/*.{scss,sass}'
],
tasks: 'compass reload'
}
}
I think i have seen a commandline flag, but I was unable to find it.
Yeoman Livereload consists of two parts: the middleware that inserts the livereload snippet, and the livereload target in the watch task. To disable livereload, remove both:
Livereload snippet at the top of the Gruntfile:
// Generated on ...
'use strict';
var LIVERELOAD_PORT = 35729; // <- Delete this
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT}); // <- Delete this
var mountFolder = function (connect, dir) {
return connect.static(require('path').resolve(dir));
};
Livereload task in Watch:
watch: {
// Delete this target
livereload: {
options: {
livereload: LIVERELOAD_PORT
},
files: [
//...
]
}
}
And the middleware that inserts the snippet:
connect: {
options: {
port: 9000,
hostname: 'localhost'
},
livereload: {
options: {
middleware: function (connect) {
return [
lrSnippet, // <- Delete this middleware
mountFolder(connect, '.tmp'),
mountFolder(connect, yeomanConfig.app)
];
}
}
For updates on fixing the livereload-connect issues in Yeoman, track this issue: https://github.com/yeoman/generator-webapp/issues/63

Resources