Grunt express livereload and proxy does not work? - express

I want to launch a web server from grunt with livereload and that proxies Rest calls towards the server.
Here is my Gruntfile.js :
var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest;
module.exports = function(grunt) {
// Load Grunt tasks declared in the package.json file
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
// 1. Toutes les configurations vont ici:
grunt.initConfig({
pkg : grunt.file.readJSON('package.json'),
watch: {
all: {
files: 'webapp/*',
options: {
livereload: true,
}
},
},
express : {
all : {
options : {
bases : 'webapp',
port : 3000,
debug:true,
hostname : "0.0.0.0",
livereload : true,
middleware: function (connect, options) {
return [proxySnippet];
}
},
}
},
connect: {
proxies: [{
context: '/sis.cata/rest',
host: 'localhost',
port: 8080,
https: false,
changeOrigin: false,
xforward: false
}],
},
grunt.registerTask('develop', ['configureProxies:connect', 'express:all', 'watch' ]);};
Static files are served but calls to REST services are not proxied and blocks.
Any ideas ?
I have seen solutions with connect and proxy that works fine but never with livereload.
Thanks a lot.

Related

Can't use proxy in Vue js

I'm a bit noob to network stuff, i'm not using vite (what ever was that), i've just created a simple proxy server in order to proxy to my vue site, i've searched tons of pages and didn't get the solution and yes when u guys see the error it will look simple, trust me i've checked the old endpoint URL znd it matches the resulting URL of the proxy, they point to the same place
this is the code to fetch the server:
async fetchtasks() {
const res = await fetch("api/tasks");
const data=res.json()
return data;
},
code in vue.config.js:
module.exports = {
devServer: {
proxy: {
'^/api': {
target: 'http://localhost:5000',
changeOrigin: true,
pathRewrite: { '^/api': '/api' },
logLevel: 'debug',
ws: true,
},
},
}
};
when i use 'http://localhost:5000' it works well but after i replace it with api it returns the "unexpected token < in json error", i know it's an html page, how do i get rid of it? the code is right, and i've tried different tweaks... nothing worked
module.exports = {
devServer: {
proxy: {
'^/api': {
target: process.env.VUE_APP_BASE_URL_API,
pathRewrite: { '^/api': '' }
}
}
}
}

Socksjs infinite loop with vue.js

I'm using vue.js with a flask server.
The 8080 vue.js dev env forwards axios queries to port 80 , cause my python flask server is always running on port 80, waiting for web services calls.
This is my vue.js vue.config.js file :
module.exports = {
outputDir: "dist",
// relative to outputDir
assetsDir: "static" ,
devServer: {
proxy: 'http://localhost:80'
}
};
everything works except that Im getting sock-js infinite loops, especially when developping on port 8080 :
How can I stop theses queries, please .
I there any way to only forwards AXIOS queries to port80, not the others things ?
https://github.com/webpack/webpack-dev-server/issues/1021
EDIT : Tried this with no luck
vue.config.js :
module.exports = {
outputDir: "dist",
// relative to outputDir
assetsDir: "static",
devServer: {
proxy: {
"^/api": {
target: "http://localhost:80"
}
}
}
};
error :
Error: Request failed with status code 404
EDIT : Hey Guys, finally resolved with this code , simply write this in your vue.config.js at the root of the vue.js app, so the wrong sockjs-node queries will get ignored, only web services will be forwarded :
module.exports = {
outputDir: "dist",
assetsDir: "static",
devServer: {
proxy: {
"/api": {
target: "http://localhost:80"
}
}
}
};
Then, do an axios query from vue.js like this :
const path = '/api/read_linear_solution';
axios.post(path, this.form)
Then, in ur python or node server , the web service must look like this 👍
#app.route('/api/read_linear_solution', methods=['POST'])

Devserver Proxy w/ Axios

I cannot seem to get the devServer: proxy setting working in my vue / express app.
My vue.config.js file is in the root of my client folder and looks like:
module.exports = {
devServer: {
proxy: {
'api': {
target: 'http://localhost:5000'
}
}
},
transpileDependencies: [
'vuetify'
]
}
I'm sending a request from the frontend using axios like this:
const response = await http.get("/api/auth/authenticate");
My express app is running on localhost:5000 and I've configured endpoints as such:
...other endpoints
app.use("/api/auth", authController);
The request appears in my network tab as:
Request URL: http://localhost:8080/api/auth/authenticate
and returns a 404 error.
What am I missing here?
Since now it is not fetching from your backend, but searching for some static content (hitting 8080, vue must be running on this port). Try using, so that it get redirected to proxy:
proxy: {
'^/api': {
target: 'http://localhost:5000',
ws: false,
changeOrigin: true
},
Or just '/api' instead of '^/api'

Workbox Webpack Plugin and Webpack Dev Server issue

I'm starting to use webpack-workbox-plugin to inject service worker into application. My project is an ASP.NET Core web application that runs over IIS Express.
This is my development webpack config file:
const MODULE_BUILD_DIR = path.resolve(__dirname, './wwwroot/dist/assets/');
const workboxPlugin = require('workbox-webpack-plugin');
process.env.NODE_ENV = "development";
const config = {
mode: "development",
target: "web",
devtool: "cheap-module-source-map",
context: __dirname, // string (absolute path!)
entry: [
'#babel/polyfill',
'font-awesome/scss/font-awesome.scss',
'./wwwroot/js/main.js',
],
output: {
path: MODULE_BUILD_DIR,
filename: '[name].bundle.js',
chunkFilename: '[id].chunk.js',
},
// ...
plugins: [
// ...
new workboxPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: true,
}),
],
devServer: {
contentBase: path.resolve(__dirname, './'),
historyApiFallback: false,
inline: true,
open: false,
port: 9099,
hot: true,
https: true,
},
// ...
}
And this is the function i call over my main.js:
export default function setServiceWorker() {
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register('/sw.js').then((registration) => {
console.log('SW registered: ', registration);
}).catch((registrationError) => {
console.log('SW registration failed: ', registrationError);
});
});
}
}
But when i run application, client doesn't find sw.js file becuse it's allocated over webpack dev server path, so not in IIS Express app path.
DevTool messages:
A bad HTTP response code (500) was received when fetching the script.
---
SW registration failed: TypeError: Failed to register a ServiceWorker
for scope ('https://localhost:44357/') with script ('https://localhost:44357/sw.js'):
A bad HTTP response code (500) was received when fetching the script.
What could be a solution for it?
Thank you
Solved using clean-webpack-plugin and write-file-webpack-plugin:
plugins: [
new CleanWebpackPlugin(),
new WorkboxPlugin.GenerateSW({
swDest: 'sw.js',
clientsClaim: true,
skipWaiting: true,
}),
new WriteFilePlugin(),
],
but not sure it's the best way

karma/jasmine to test an angular app, can't inject

I spent few hours on this issue and can't find what's wrong, I'm using karma/jasmine to create test in my angular app. I use, or at least try to use angular-mock to inject and test my controllers but I get this error :
Error: [$injector:unpr] Unknown provider: ENVProvider <- ENV
http://errors.angularjs.org/1.3.17/$injector/unpr?p0=ENVProvider%20%3C-%20ENV
in my test
describe('controllers', function(){
beforeEach(module('myModule'));
var $controller;
beforeEach(inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.testMessage', function() {
it('check the test message is ok', function() {
//TODO
});
});
});
So I suppose it's the inject call which cause the issue
here is my karma.conf.js
'use strict';
module.exports = function(config) {
var configuration = {
autoWatch : true,
frameworks: ['jasmine'],
ngHtml2JsPreprocessor: {
stripPrefix: 'src/',
moduleName: 'hematiteFront'
},
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-chrome-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
files: [
'bower_components/jquery/dist/jquery.js',
'bower_components/angular/*.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-ui-router/release/angular-ui-router.js',
'bower_components/angular-materialize/js/*.js',
'bower_components/angular-materialize/src/*.js',
'bower_components/angular-translate/angular-translate.js',
'bower_components/angular-translate-loader-partial/angular-translate-loader-partial.js',
'bower_components/angular-translate-storage-cookie/angular-translate-storage-cookie.js',
'bower_components/angular-mocks/angular-mocks.js',
'src/**/*.js'
],
logLevel: 'LOG_ERROR',
exclude: [
'src/app/app.constants.js',
'bower_components/**/index.js',
'bower_components/**/*.min.js'
],
preprocessors: {
'src/**/*.html': ['ng-html2js']
}
};
config.set(configuration);
};
Any idea or piece of advice would be more than wellcome
thanks