How to run both svelte and go - 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.

Related

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

How to detect Development mode within Svelte code? [duplicate]

The dev mode using npm run dev, the release mode using npm build
How could i know that it's currently built on dev mode or not in the code, for example:
<script>
import {onMount} from 'svelte';
onMount(function(){
if(DEVMODE) { // --> what's the correct one?
console.log('this is x.svelte');
}
})
</script>
If you are using sveltekit:
import { dev } from '$app/environment';
if (dev) {
//do in dev mode
}
Not sure about the correct method. I share what I did on my project.
in rollup.config.js
import replace from "#rollup/plugin-replace";
const production = !process.env.ROLLUP_WATCH;
inside plugins:[ ] block add this
replace({
isProduction: production,
}),
rollup.config.js will look like this.
},
plugins: [
replace({
isProduction: production,
}),
svelte({
Then use isProduction inside components .
if (!isProduction){ console.log('Developement Mode'); }
If you are using Svelte with Vite, you may use:
import.meta.env.DEV - true in development environment.
import.meta.env.PROD - true in production environment.
import.meta.env.MODE - name of the mode, if you need more control.
See Vite docs on Env variables
I solved this problem by checking the hostname the application is running on.
You can also use other forms like, port or even msm a localStore browser variable.
Note that I check if the application is running on the client side before using the 'window'
const isProduction = (): boolean => {
// Check if is client side
if (typeof window !== 'undefined' && window.document !== undefined) {
// check production hostname
if (window?.location.hostname !== undefined &&
window.location.hostname === 'YOUR_PRODUCTION_HOSTNAME') {
return true
} else {
return false
}
} else {
return false
}
}
When using Svelte (not svelte-kit), this worked for me inside svelte components:
<script>
let isProduction = import.meta.env.MODE === 'production';
if (!isProduction) {
console.log("Developement Mode");
} else {
console.log("Production Mode");
}
</script>
Thanks timdeschryver for the reference

Is it possible to get webpack-dev-server to ignore all but a certain path in the proxy settings?

I've got my WDS running on port 9000, and the webpack bundles located under /dist/ I've got a back end server running on port 55555
Is there a way to get WDS to ignore (proxy to 55555) every call except those starting with /dist/?
I've got the following:
devServer: {
port: 9000,
proxy: {
"/dist": "http://localhost:9000",
"/": "http://localhost:55555"
}
}
Trouble is, that root ("/") just overrides everything...
Thanks for any advice you can offer.
UPDATE:
I've gotten a little farther with the following:
proxy: {
"/": {
target: "http://localhost:55555",
bypass: function(req, res, proxyOptions) {
return (req.url.indexOf("/dist/") !== -1);
}
}
},
But the bypass just seems to kill the connection. I was hoping it would tell the (9000) server to not proxy when the condition is true. Anybody know a good source explaining "bypass"?
Webpack allows glob syntax for these patterns. As a result, you should be able to use an exclusion to match "all-but-dist".
Something like this may work (sorry I don't have webpack in front of me at the moment):
devServer: {
port: 9000,
proxy: {
"!/dist/**/*": "http://localhost:55555"
}
}

Using webpack dev server, how to proxy everything except "/app", but including "/app/api"

Using webpack dev server, I'd like to have a proxy that proxies everything to the server, except my app. Except that the api, which has an endpoint under my app, should be proxied:
/myapp/api/** should be proxied
/myapp/** should not be proxied (any
/** should be proxied
The following setup does this using a bypass function, but can it be done declaratively, using a single context specification?
proxy: [
{
context: '/',
bypass: function(req, res, options) {
if (
req.url.startsWith('/app') &&
!req.url.startsWith('/app/api')
) {
// console.log ("no proxy for local stuff");
return false;
}
// console.log ("Proxy!")
},
// ...
},
],
According to https://webpack.js.org/configuration/dev-server/#devserver-proxy webpack dev server uses http-proxy-middleware and at its documentation (https://github.com/chimurai/http-proxy-middleware#context-matching) you can use exclusion.
This should be working in your case:
proxy: [
{
context: ['**', '/myapp/api/**', '!/myapp/**'],
// ...
},
],

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