Having problems to add SSL to nuxt-axios web app on DOCKER - 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.

Related

NestJS, Vue and nginx in different docker containers gives an CORS error

NestJS container with enabled CORS:
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '#nestjs/common';
import * as cors from 'cors';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.use(cors({ origin: '*' }));
app.useGlobalPipes(new ValidationPipe());
await app.listen(8802);
}
bootstrap();
Vue container with requests to adress: https://api:8802
Error messages:
In Firefox:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource
In Chrome:
net::ERR_HTTP2_PROTOCOL_ERROR
I tried everything and nothing works
As per the NestJS docs, you should be able to use:
app.enableCors();
Or:
const app = await NestFactory.create(AppModule, { cors: true });
Instead of:
app.use(cors({ origin: '*' }));

Ionic 5 - API request working on browser, not on emulated IOS

I have this Ionic 5/Capacitor app, which I'm making an API call to a local server from, that server running on docker at localhost:3000. When I test from the browser, the request is made fine. From Postman it requests fine, too. In my XCode logs the emulator, I see this
[error] - ERROR {"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":"http://localhost:3000/pins","ok":false,"name":"HttpErrorResponse","message":"Http failure response for http://localhost:3000/pins: 0 Unknown Error","error":{"isTrusted":true}}
The really interesting part, is that I'm running Fiddler to monitor the request as it's made. Fiddler gets a 200 as well, I can even see the response data. So, Fiddler sees the proper network call, but then my Ionic app gets that error. That makes me feel like it's an Ionic/Emulator/IOS problem, but I don't have enough familiarity with Ionic to know right off the bat what it is.
Here's the code responsible for making the request:
ngOnInit() {
const request = this.http.get('http://localhost:3000/pins');
this.refresh$.subscribe(
(lastPos: { latitude?: any; longitude?: number }) => {
request.subscribe(data => {
if (data) {
this.addMarkersToMap(data, lastPos);
}
});
}
);
}
And the HTTPClient imported in the constructor is from Angular:
import { HttpClient } from '#angular/common/http';
I ended up having to use this package, doing a check on if I'm on mobile or not.
https://ionicframework.com/docs/native/http/
Try with this :
const request = this.http.get('http://localhost:3000/pins', { observe: 'response', withCredentials: true });
Solution 2 : capacitor.config.json
"server": {
"hostname": "localhost", (maybe try precising the port number too)
}
Solution 3 : On your Express server (from https://ionicframework.com/docs/troubleshooting/cors)
const express = require('express');
const cors = require('cors');
const app = express();
const allowedOrigins = [
'capacitor://localhost',
'ionic://localhost',
'http://localhost',
'http://localhost:8080',
'http://localhost:8100'
];
// Reflect the origin if it's in the allowed list or not defined (cURL, Postman, etc.)
const corsOptions = {
origin: (origin, callback) => {
if (allowedOrigins.includes(origin) || !origin) {
callback(null, true);
} else {
callback(new Error('Origin not allowed by CORS'));
}
}
}
// Enable preflight requests for all routes
app.options('*', cors(corsOptions));
app.get('/', cors(corsOptions), (req, res, next) => {
res.json({ message: 'This route is CORS-enabled for an allowed origin.' });
})
app.listen(3000, () => {
console.log('CORS-enabled web server listening on port 3000');
});

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?

How do I get webpack-dev-server to accept POST requests

In my project I call:
$ webpack-dev-server --history-api-fallback
And it starts an express server (I'm assuming) available on localhost:8080.
It works great except that I want to submit a form via POST into an iframe loading my app; localhost:8080 in development and something else in production.
I don't expect to do anything with that POST data in development, but in production, it needs to be POST.
When I try to use POST however, it cannot find POST /
Is there a configuration option or some other solution that will allow me to use the webpack-dev-server? (I really don't want to have to write my own server for this).
#cowCrazy had half of the story, but didn't show how to respond with the same response for GET in the case of POST, which is what I was looking for.
In the Webpack config, you do this:
module.exports = {
...,
devServer: {
setup(app) {
app.post('*', (req, res) => {
res.redirect(req.originalUrl);
});
},
}
}
This will just take the POST URL and redirect with the same URL, making it a GET request.
Instead of having a server error, it will redirect with GET.
What you are looking for is devServer. Bellow you can see my config for it. Under setup(app) you can add "almost" whatever you want:
module.exports = {
...,
devServer: {
inline: true,
port: 3000,
publicPath: '/',
setup(app){
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.get("/get/some-data", function(req, res){
console.log(req);
res.send("GET res sent from webpack dev server")
})
app.post("/post/some-data", bodyParser.json(), function(req, res){
console.log(req.body);
res.send("POST res sent from webpack dev server")
})
}
}
}
EDIT:
I have pushed a minimalistic example to github if you wanna take a better look.
Check if it solves your problem by converting the POST request to GET request:
bypass: function (req, res, proxyOptions) {
const url = req.url;
req.method = 'GET';
if (url.indexOf('?') > -1) {
return url.replace('?', '.json?');
} else {
return url + '.json';
}
}

Grunt Livereload + Grunt Connect Proxy

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

Resources