Minimal example of using grunt-connect-proxy - proxy

I have an angularJs App which I built with grunt and a server backend written in Java running on a tomcat server. To wire those together when development I wanted to use grunt-connect-proxy. But I could not get it to work even a bit.
All the "examples" and "demos" I found on the web happened to use a several hundred lines long Gruntfile.js. That turned out not to be really useful in finding my problem. What does a minimal (!) example look like?

This is how you can create a minimal demo which is just a proxy to google.com:
Run:
npm install grunt-connect-proxy --save-dev
npm install grunt-contrib-connect --save-dev
and creat the following Gruntfile.js:
module.exports = function (grunt) {
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
grunt.initConfig({
connect: {
server: {
options: {
hostname: 'localhost',
keepalive: true,
open: true,
middleware: function (connect, options) {
return [proxySnippet];
}
},
proxies: [{
context: '/',
host: 'google.com',
port: 80
}]
}
}
});
grunt.loadNpmTasks('grunt-connect-proxy');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.registerTask('default', [
'configureProxies:server',
'connect:server']);
};
Now just run grunt.

Related

How to run both svelte and go

I'm trying to make a website using svelte(front) and golang(backend).
My problem is when I run those in different terminal to test my app('npm go dev' for svelte, 'go run .' for go), they run in different port. Go in port 8080 and Svelte in port 50838. How can I solve this?
Using vite to proxy requests to your Go backend is probably the simplest method (I'm assuming you are using vite!).
To do this add something like the following to your vite.config.js:
const config = {
...,
server: {
proxy: {
'/api': {
target: 'http://127.0.0.1:8080/',
proxyTimeout: 10000
},
'/': { // Complex example that filters based on headers
target: 'http://127.0.0.1:8080/',
proxyTimeout: 600000,
bypass: (req, _res, _options) => {
let ct = req.headers['content-type'];
if (ct == null || !ct.includes('grpc')) {
return req.url; // bypass this proxy
}
}
}
},
}
};
This contains a few examples; you will need to tweak these to meet your needs.

HMR tls issues with Visual Studio 2022 Vue template

I am using the Microsoft Vue tutorial to create a solution with separate frontend and backend projects. I am using the default configuration that enables tls and I have trusted the IIS Express Development Certificate, but the frontend project appears to use the public IP address in hmr requests which are not included in the dev certificate that is based on localhost only.
My vue.config.js is as follows:
const fs = require('fs')
const path = require('path')
const HttpsAgent = require('agentkeepalive').HttpsAgent
const baseFolder =
process.env.APPDATA !== undefined && process.env.APPDATA !== ''
? `${process.env.APPDATA}/ASP.NET/https`
: `${process.env.HOME}/.aspnet/https`
const certificateArg = process.argv.map(arg => arg.match(/--name=(?<value>.+)/i)).filter(Boolean)[0]
const certificateName = certificateArg ? certificateArg.groups.value : 'WebAppFrontend'
if (!certificateName) {
console.error('Invalid certificate name. Run this script in the context of an npm/yarn script or pass --name=<<app>> explicitly.')
process.exit(-1)
}
const certFilePath = path.join(baseFolder, `${certificateName}.pem`)
const keyFilePath = path.join(baseFolder, `${certificateName}.key`)
module.exports = {
devServer: {
// host: 'localhost',
https: {
key: fs.readFileSync(keyFilePath),
cert: fs.readFileSync(certFilePath),
},
proxy: {
'^/weatherforecast': {
target: 'https://localhost:5001/',
changeOrigin: true,
agent: new HttpsAgent({
maxSockets: 100,
keepAlive: true,
maxFreeSockets: 10,
keepAliveMsecs: 100000,
timeout: 6000000,
freeSocketTimeout: 90000
}),
onProxyRes: (proxyRes) => {
const key = 'www-authenticate'
proxyRes.headers[key] = proxyRes.headers[key] && proxyRes.headers[key].split(',')
}
}
},
port: 5002
}
}
I tried to manually set the webpack host option to localhost but Visual Studio cannot start the backend project. If I modify the startup projects from both the front and backend projects to just the backend and then execute npm run serve manually, everything works fine.
How do I force the SockJS calls to use localhost instead of the public IP address without breaking the Visual Studio debugging setup?
Just fix same Error. Try this
in vue.config.js
module.exports = {
devServer: {
host: '0.0.0.0',
public: '0.0.0.0:5002',
disableHostCheck: true,
I am using #vue/cli 5.0.4 in a project with webpack-dev-server#4.9.0
I tried the solution from #asp.entwickler but got some errors because disableHostCheck and public have been deprecated.
According to https://cli.vuejs.org/migrations/migrate-from-v4.html#vue-cli-service
webpack-dev-server has been updated from v3 to v4. So there are breaking changes with regard to the devServer option in vue.config.js.
The disableHostCheck option was removed in favor allowedHosts: 'all';
public, sockHost, sockPath, and sockPort options were removed in favor client.webSocketURL option.
so the solution was to set devServer.client.webSocketURL.hostname. Also setting allowedHosts: 'auto' instead of 'all' seems to be a good idea unless you really need it.
When set to 'auto' this option always allows localhost, host, and client.webSocketURL.hostname:
module.exports = {
devServer: {
allowedHosts: 'auto',
client: {
webSocketURL:
{
hostname: 'localhost'
}
},

Laravel mix 6 hot with https

Configuration:
Laravel Mix 6.0.16
Laravel Valet 2.13.19
webpack 5.30.0
webpack-cli 4.6.0
webpack-dev-server 4.0.0-beta.1
Description:
I try to enable https for hot replacement in Laravel 8 on MacOs with Valet. I did my site secure, add --https in my package.json
"hot": "mix watch --hot --https"
Then I launch command in CLI
yarn hot
And it was successful, but when I open my site I saw error in browser console http://joxi.ru/nAypq4ZTwJBP52
net::ERR_CERT_AUTHORITY_INVALID
I found the solution.
Remove --https from script definition in package.json
Add configuration in the file webpack.mix.js
mix.options({
hmrOptions: {
host: url,
port: 8080
}
})
mix.webpackConfig({
devServer: {
https: {
key: fs.readFileSync('/Users/alex/.config/valet/Certificates/castle.test.key'),
cert: fs.readFileSync('/Users/alex/.config/valet/Certificates/castle.test.crt')
}
}
})
In my case I got the mixed content issue. I found out the publicPath was still using http instead of https. I fixed the public path by overriding it. Also made added a few checks to read the certificates if they exist and made the certificate path generic.
const homeDir = process.env.HOME;
const host = process.env.APP_URL.split('//')[1];
const port = '8080';
mix.options({
hmrOptions: {
host,
port
}
});
if (
process.argv.includes("--hot") &&
fs.existsSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.key`)) &&
fs.existsSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.crt`))
) {
mix.webpackConfig({
devServer: {
https: {
key: fs.readFileSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.key`)).toString(),
cert: fs.readFileSync(path.resolve(homeDir, `.config/valet/Certificates/${host}.crt`)).toString()
},
}
});
// overriding publicPath as it was using http and causing mixed-content
mix.override(c => {
c.output.publicPath = process.env.APP_URL + `:${port}/`
});
}
Update
laravel-mix-valet is available on npm which works with laravel valet
require('laravel-mix-valet');
const host = process.env.APP_URL.split('//')[1];
mix.js('resources/js/app.js', 'public/js')
.valet(host)
.vue();
This works for our team (running "hot": "mix watch --hot", without the --https):
if (!mix.inProduction() && process.env.DEV_SERVER_KEY) {
let proxy = process.env.APP_URL.replace(/^(https?:|)\/\//,'');
mix.options({
hmrOptions: {
host: proxy,
port: '8080',
https: {
key: process.env.DEV_SERVER_KEY,
cert: process.env.DEV_SERVER_CERT
}
}
});
}

VuePress: How can I use https in dev server?

Is there any hook to enable https in VuePress dev server?
1. Current solution.
I directly add one line to node_modules/#vuepress/core/lib/node/dev/index.js. This works well, but nasty.
createServer () {
const contentBase = path.resolve(this.context.sourceDir, '.vuepress/public')
const serverConfig = Object.assign({
https: true, // <--- Added this line.
disableHostCheck: true,
compress: true,
clientLogLevel: 'error',
vuejs/vuepress - /packages/#vuepress/core/lib/node/dev/index.js#L197-L237
2. Background
Because Chrome has changed it's security policy, CORS.
3. What I've tried.
I've tried but not working.
webpack - devServer.https
docs/.vuepress/config.js
configureWebpack: (config, isServer) => {
if (!config.devServer) {
config.devServer = {}
}
Object.assign(config.devServer, {
https: true,
})
}
No proper hook
VuePress - Plugin Option API - beforeDevServer
VuePress - Plugin Option API - afterDevServer
No command option for https.
vuejs/vuepress - /packages/vuepress/lib/registerCoreCommands.js#L18-L31
module.exports = function (cli, options) {
cli
.command(`dev [targetDir]`, 'start development server')
.option('-p, --port <port>', 'use specified port (default: 8080)')
.option('-t, --temp <temp>', 'set the directory of the temporary file')
.option('-c, --cache [cache]', 'set the directory of cache')
.option('--host <host>', 'use specified host (default: 0.0.0.0)')
.option('--no-cache', 'clean the cache before build')
.option('--no-clear-screen', 'do not clear screen when dev server is ready')
.option('--debug', 'start development server in debug mode')
.option('--silent', 'start development server in silent mode')
.option('--open', 'open browser when ready')
.action((sourceDir = '.', commandOptions) => {
const { debug, silent } = commandOptions
4. Related links.
vuejs/vuepress - Support devServer.proxy in configureWebpack #858
vuejs/vuepress - Sunsetting webpack-serve #1195
Add the following settings to config.js.
//
// docs/.vuepress/config.js
//
module.exports = {
devServer: {
https: true
},
}
How to run Vue.js dev serve with https? - Stackoverflow
Thank you for your guidance in many ways.

Getting Babel 6 to work with IE8 (via. Gulp/Webpack)

I've got Babel 6 working nicely with Gulp and Webpack. I now need to polyfill it to get IE8 support.
I've installed the babel-polyfill, but can't get it working and the docs and Google haven't helped so far.
My Gulp task (inc. Webpack config):
gulp.task('webpack', function(callback) {
var webpackConfig = {
context: __dirname + '../../../js',
entry: {
homepage: [
'babel-polyfill',
'./public/homepage/homepage.js'
]
},
output: {
path: __dirname + '../../../dist/public/scripts/',
filename: '[name].bundle.js'
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/, // Only run .js files through Babel
include: /js/, // Only include the /js dir
query: {
//plugins: ['transform-runtime'], // Disabled pending fix to https://github.com/babel/babel/issues/2954
presets: ['es2015'],//, 'stage-0'
}
}
]
}
};
webpack(webpackConfig, function(err, stats) {
if (err) {
throw new gutil.PluginError('webpack', err);
}
gutil.log('[webpack]', stats.toString({
// output options
}));
callback();
});
});
From the docs (https://babeljs.io/docs/usage/polyfill/):
Usage in Node / Browserify / Webpack
To include the polyfill you need to require it at the top of the entry point to > your application.
require("babel-polyfill");
Usage in Browser
Available from the dist/polyfill.js file within a babel-polyfill npm release. This needs to be included before all your compiled Babel code. You can either prepend it to your compiled code or include it in a before it.
NOTE: Do not require this via browserify etc, use babel-polyfill.
I've tried simply adding the polyfill.js file to the top of the page, but IE8 still isn't happy with the compiled code's use of the default keyword.
I've also tried adding the polyfill to the webpack process, as per http://jamesknelson.com/using-es6-in-the-browser-with-babel-6-and-webpack/ and other suggestions from Google
What am I doing wrong?

Resources