VuePress: How can I use https in dev server? - https

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.

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

Heroku deploy chat bot

so, my code works both locally and docker image but, when I deploy to heroku it seems to work on first 1 minute and then app crashes, there is heroku logs, after crashing so what can be problems? any thought? thank you
there is my code
const { default: axios } = require('axios')
const telegramBot = require('node-telegram-bot-api')
const express = require('express')
const dotenv = require('dotenv').config()
const links = `
GitLab
Linkdin
Personal
`
const bot = new telegramBot(process.env.TOKEN, { polling: true })
const aboutText = 'Hello, I am learning NODE JS!'
const app = express()
bot.on('message', (message) => {
const id = message.chat.id
if (message.text === '/start' || message.text === '/help') {
bot.sendMessage(message.chat.id, 'avalable commands', {
reply_markup: {
keyboard: [['/about', '/links']],
resize_keyboard: true,
one_time_keyboard: true,
force_reply: true,
},
})
} else if (message.text === '/about') {
bot.sendMessage(id, aboutText)
} else if (message.text === '/links') {
bot.sendMessage(id, links, { parse_mode: 'HTML' })
} else {
bot.sendMessage(
message.chat.id,
'no such command! there are avalable commands',
{
reply_markup: {
keyboard: [['/about', '/links']],
resize_keyboard: true,
one_time_keyboard: true,
force_reply: true,
},
}
)
}
})
dockerfile:
FROM node:16-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY ./app.js .
ENV port=8080
ENV TOKEN=21*****:AAEF******************fKiQ
EXPOSE 8080
CMD [ "node", "app.js" ]
Your app fails to bind to the port assigned by Heroku: you cannot set the port yourself (ie 8080) but instead bind to the port defined by the $PORT env variable.
See Why is my Node.js app crashing with an R10 error? to understand the details.
In your specific case if you run the Bot in polling mode (i.e. pulling the changes) you can instead use a worker node instead of a web: doing this you don't need to bind to the port as your application does not require to process incoming HTTP requests.

Protractor file download test fails when headless chrome

I am having an issue with a protractor test. It was working, but now (even thought nothing has changed) it is not.
The test is just opening the app (web application) and clicking on a button to download an image. The download should start straight away.
The problem is that the next instruction after the download event throws an exception, Failed: chrome not reachable. I am using the latest chrome and chrome driver versions.
The capabilites section for protractor is like this:
capabilities: {
browserName: 'chrome',
loggingPrefs: { browser: 'ALL' },
chromeOptions: {
args: ['--headless', '--window-size=1240,780'],
},
}
I am reading about using DevTools to enable downloads in headless mode (Page.setDownloadBehavior), but so far no luck.
Does anybody have this issue too? Any clue how to fix it?
Thanks.
There could be another easy way to do it, but this is what I have done in my test suite.
I used got library, however, you can use any library to send an HTTP post request.
Discussion about setting download directory in headless chrome: https://bugs.chromium.org/p/chromium/issues/detail?id=696481
let got = require('got');
let session = await browser.getSession();
let sessionId = session['id_'];
let params = {'cmd': 'Page.setDownloadBehavior', 'params': {'behavior': 'allow', 'downloadPath': downloadDir }}
await got.post('http://localhost:4444/wd/hub/session/'+ sessionId + '/chromium/send_command', {body: JSON.stringify(params)})
If you have not disabled ControlFlow in your protractor config, change ASync/Await to .then.
An easier solution is to add these lines to your protractor.conf.js:
exports.config = {
...
onPrepare() {
...
browser.driver.sendChromiumCommand('Page.setDownloadBehavior', {
behavior: 'allow',
downloadPath: downloadsPath
});
}
};
From: https://bugs.chromium.org/p/chromium/issues/detail?id=696481#c196
Appendix
If you are to lazy to find a Download Path just paste this at the top of your protractor.conf.js:
var path = require('path');
var downloadsPath = path.resolve(__dirname, './downloads');
It will download the file to the e2e/downloads folder. Just use the same code in your tests to find out if the file downloaded.
This works for me:
chromeOptions: {
'args': [
'--headless',
'--disable-gpu',
'--test-type=browser',
'--disable-extensions',
'--no-sandbox',
'--disable-infobars',
'--window-size=1920,1080',
//'--start-maximized'
"--disable-gpu",
],
prefs: {
'download.default_directory': 'C:\\downloads',
'download.prompt_for_download':false,
'download.directory_upgrade':true,
"safebrowsing.enabled":false,
"safebrowsing.disable_download_protection":true
},
},

No provider for Jasmine-jquery?

I'm using Yeoman+Angular Generator for my application and I have been running around hard to get along with Jasmine! This is where I am stuck. I want to be able to use jQuery selectors with Jasmine tests. I have installed the karma-jasmine and karma-jasmine-jquery packages. Then I installed it for bower (I'm new and I have no idea what should be installed for what!). I have manually added the path in my karma.conf.js, but I still get the message that says this:
Running "karma:unit" (karma) task
Warning: No provider for "framework:jasmine-jquery"! (Resolving: framework:jasmine-jquery) Use --force to continue.
This is how my karma config looks like:
// Karma configuration
// http://karma-runner.github.io/0.12/config/configuration-file.html
// Generated on 2014-09-12 using
// generator-karma 0.8.3
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine-jquery', 'jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/jasmine-jquery/lib/jasmine-jquery.js',
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-animate/angular-animate.js',
'bower_components/angular-cookies/angular-cookies.js',
'bower_components/angular-resource/angular-resource.js',
'bower_components/angular-route/angular-route.js',
'bower_components/angular-sanitize/angular-sanitize.js',
'bower_components/angular-touch/angular-touch.js',
'bower_components/angular-bootstrap/ui-bootstrap.js',
'app/scripts/**/*.js',
//'test/mock/**/*.js',
'test/spec/**/*.js',
'app/views/*.html'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
preprocessors: {
'app/views/*.html': 'ng-html2js'
},
ngHtml2JsPreprocessor: {
stripPrefix: 'app/',
moduleName: 'views'
},
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
I had the same problem as this. Fixed it by adding karma-jasmine-jquery to the plugins array in karma.conf.js. This is my karma.conf in full.
module.exports = function(config) {
'use strict';
config.set({
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// base path, that will be used to resolve files and exclude
basePath: '../',
// testing framework to use (jasmine/mocha/qunit/...)
frameworks: ['jasmine-jquery', 'jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/scripts/**/*.js',
'test/mock/**/*.js',
'test/spec/**/*.js'
],
// list of files / patterns to exclude
exclude: [],
// web server port
port: 8080,
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers: [
'PhantomJS'
],
// Which plugins to enable
plugins: [
'karma-phantomjs-launcher',
'karma-jasmine-jquery',
'karma-jasmine',
],
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun: false,
colors: true,
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel: config.LOG_INFO,
// Uncomment the following lines if you are using grunt's server to run the tests
// proxies: {
// '/': 'http://localhost:9000/'
// },
// URL root prevent conflicts with the site root
// urlRoot: '_karma_'
});
};
The other change I made is that as per the jasmine-jquery docs it requires jasmine version of at least 0.2.0. The generator gives version of 0.1.5 (at least it did for me yesterday). So to fix this I ran 'npm install karma-jasmine#0.2.0 --save-dev'. The save dev should do this but make sure you have the correct packages listed in the devDependencies in the root package.json for me I have:
"karma-jasmine": "^0.2.0",
"karma-jasmine-jquery": "^0.1.1",
Obviously these should correspond with the actual packages in node-modules
Hope it helps
C

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