HMR tls issues with Visual Studio 2022 Vue template - visual-studio

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'
}
},

Related

Laravel Vite: Assets blocked/Mixed Content issues in production environment

I'm hosting my App on an EC2-instance behind an Elastic Load Balancer which manages my SSL-Certificate. On this EC2-Instance my nginx-configuration is redirecting all http-Requests to https.
I recently switched to Vite which caused me a lot of trouble. When I push my app to the server after calling npm run build my assets are blocked. In the browser console I get:
Mixed Content: The page at 'example.com' was loaded over HTTPS, but requested an insecure ...
My Setup:
vite.config.js
export default defineConfig({
server: {
host: 'localhost',
},
plugins: [
laravel([
'resources/assets/sass/app.sass',
// etc...
]),
vue({
template: {
transformAssetUrls: {
base: null,
includeAbsolute: false,
},
},
}),
],
});
Setting "https: true" in the server-block didn't help me.
.env
APP_ENV=production
APP_URL=https://example.com
ASSET_URL=https://example.com
In my blade template I'm using the Vite-directive:
#vite('resources/assets/sass/app.sass')
I tried the following solutions:
Setting $proxies = '*' in TrustProxies.php, which doesn't have any effect.
Setting URL::forceScheme('https'); in AppServiceProvider.php, which will load the assets but lead to a lot of other issues.
Somehow the #vite-directive is not resolving my assets as secure assets. With Laravel Mix I could just call secure_asset.
How can I fix this?
In the end I used the TrustedProxies-middleware. However back then I forgot to register it as global middleware.
import fs from 'fs';
const host = 'example.com';
server: {
host,
hmr: {host},
https: {
key: fs.readFileSync(`ssl-path`),
cert: fs.readFileSync(`ssl-cert-path`),
},
},
you should add this to vite.config.js file along with ASSET_URL to your .env file

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.

ERR_TOO_MANY_REDIRECTS on vercel after deploying Nextjs App

I deployed my nextjs app to Vercel and it was a success.
I can see a preview of the website and even the log saying it works well.
But i try to access the website via the default Vercel domain :
https://tly-nextjs.vercel.app/
I get an ERR_TOO_MANY_REDIRECTS.
I do not have this problem locally.
I tried :
Disabling a language redirect that I use (/en for english folks, and / for french people).
Disabling the language detector of i18next.
But none of these solutions changed anything.
Any ideas ?
i18n.js file
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Cache from 'i18next-localstorage-cache';
import LanguageDetector from 'i18next-browser-languagedetector';
const fallbackLng = ['fr'];
const availableLanguages = ['fr', 'en'];
const en = require('./locales/en/common.json');
const fr = require('./locales/fr/common.json');
const options = {
order: ['querystring', 'navigator'],
lookupQuerystring: 'lng'
}
const cacheOptions = {
// turn on or off
enabled: true,
// prefix for stored languages
prefix: 'i18next_res_',
// expiration
expirationTime: 365*24*60*60*1000,
// language versions
//versions: {}
}
i18n
.use(Cache)
.use(initReactI18next)
.use(LanguageDetector)
.init({
cache: cacheOptions,
fallbackLng: fallbackLng,
debug: true,
detection: options,
supportedLngs: availableLanguages,
nonExplicitSupportedLngs: true,
resources: {
en: {translation: en},
fr: {translation: fr},
},
interpolation: {
escapeValue: false,
},
react: {
wait: true,
useSuspense: true,
},
});
export default i18n;
My change Language function :
const changeLanguageInHouse = (lang, bool) => {
setLoading(true);
i18next.changeLanguage(lang).then((t) => {
setLanguage(lang);
bake_cookie("langChoice", lang);
setLoading(false);
if (bool === true) {
var newUrl2 = (lang === "fr" ? "" : "/en") + asPath;
window.location.replace(newUrl2);
}
});
};
What happend at your server is following:
You enter https://tly-nextjs.vercel.app/ and it is redirected to /en with HTTP-Status-Code 307 (Temporary Redirect).
And /en redirect with 301 (Permanent Redirect) to /.
You can reproduce this by open the Browser-Dev-Tools and have a look at the Network Tab.
It might be, that you have some kind of url-rewriting activated at your server, which redirect everything to your domain-root.
Is there a public repo available for this? Here is how it worked for me.
Try changing the order of the locales and the default locale (not sure this helps, but it changed something for me. Undocumented if that is the case!)
So I put the default locale first (which is nl for me) in both the locales array and the domains array.
Let me know if that helps!
module.exports = {
i18n: {
localeDetection: false,
// These are all the locales you want to support in
// your application
locales: ['nl', 'en'],
// This is the default locale you want to be used when visiting
// a non-locale prefixed path e.g. `/hello`
defaultLocale: 'nl',
// This is a list of locale domains and the default locale they
// should handle (these are only required when setting up domain routing)
domains: [
{
domain: 'example.be',
defaultLocale: 'nl',
},
{
domain: 'example.com',
defaultLocale: 'en',
},
],
},
trailingSlash: true,
};
I changed all my getInitialProps to getServerSideProps
and realised I was doing a redirect on response :
res.writeHead(301, { Location: "/" })
I just delete it.
And now I don't have this endless redirect.
Doing this worked for me...
https://ardasevinc.tech/cloudflare-vercel-too-many-redirects
I think it's the actual solution to the cause of the problem rather than a bandage!

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.

Minimal example of using grunt-connect-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.

Resources