Why aren't my browsers console logging with WebSockets in Vue? - vue.js

I hope you can help.
I'm new to WebSockets, I've gotten a simple app running locally and now I wanted to try setting up WS with Vue but am not getting the expected behaviour. I've tried to make code as concise as possible.
I followed this tutorial: https://tutorialedge.net/javascript/vuejs/vuejs-websocket-tutorial/
Goal:
I'm trying to establish a simple WebSockets connection with Vue.
With the code below, I'm running npm run serve(see package.json file), to run my application on http://localhost:8080/.
The problem:
WebSockets connects as I expect it to but when I fire sendMessage with the button, both browsers aren't console logging, which is what I'm expecting.
I've tried changing the WS connection to this.connection = new WebSocket("ws://localhost:8080") but no luck, it never connects and remains in the connecting phase.
I'm receiving no errors in the console.
Can you please help me figure out what I'm doing wrong?
Your help is much appreciated.
Thank you
Moe
The code below is my root Vue.appfile.
<template>
<div id="app">
<button v-on:click="sendMessage">Send Message</button>
</div>
</template>
<script>
export default {
name: 'App',
components: {
testComponent
},
data: function () {
return {
connection: null
}
},
methods: {
sendMessage: function (message) {
this.connection.send(message)
}
},
created: function () {
console.log("Starting Connection to WebSockets Server.")
this.connection = new WebSocket("wss://echo.websocket.org")
this.connection.onopen = function (event) {
console.log(event)
console.log("Successfully connected to the WebSocket Server.")
}
this.connection.onmessage = function (event) {
console.log(event)
}
}
}
</script>
This is my package.json file.
{
"name": "vuejs-websocket-tutorial",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.6.5",
"vue": "^2.6.11"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.4.0",
"#vue/cli-plugin-eslint": "~4.4.0",
"#vue/cli-service": "~4.4.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"sass-loader": "^8.0.2",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}

Related

Vue3 Composition API, how to get data from service?

I'm experimenting with the Composition API with Vue3. But there were some points I couldn't find. The same code did not work in two different projects.
What I want to do in my own project is to take the data through the API and use it according to what is required. In short, do the necessary get/post operations. I got this API from Vue's own example.
This is the first project code, package.json and error message
<template>
<div class="home">
<div v-for="datas in data" :key="datas.description">
{{ datas.description }}
</div>
</div>
</template>
<script lang="ts">
import { Options, Vue } from "vue-class-component";
import axios from "axios";
import { ref } from "vue";
#Options({
props: {
msg: String,
},
})
export default class HelloWorld extends Vue {
setup() {
let data = ref([]);
axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json")
.then((res) => {
data.value = res.data.bpi;
});
}
}
</script>
{
"name": "api-project",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"vue": "^3.0.0",
"vue-class-component": "^8.0.0-0",
"vue-router": "^4.0.0-0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-router": "~4.5.0",
"#vue/cli-plugin-typescript": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"typescript": "~4.1.5"
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
Vue warn
This is the second project code, package.json, and data
<template>
<div v-for="datas in data" :key="datas.description">
{{ datas.description }}
</div>
</template>
<script lang="ts">
import axios from "axios";
import { ref } from "vue";
export default {
name: "HelloWorld",
setup() {
let data = ref([]);
axios.get("https://api.coindesk.com/v1/bpi/currentprice.json").then((res) => {
data.value = res.data.bpi;
});
return {
data,
};
},
}
</script>
{
"name": "test-api",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"vue": "^3.0.0"
},
"devDependencies": {
"#vue/cli-plugin-babel": "~4.5.0",
"#vue/cli-plugin-eslint": "~4.5.0",
"#vue/cli-service": "~4.5.0",
"#vue/compiler-sfc": "^3.0.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^7.0.0",
"node-sass": "^4.12.0",
"sass-loader": "^8.0.2",
"typescript": "~4.1.5"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/vue3-essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
my data
Could there be an error in my Composition API usage? I've heard that in some videos, "then" is not used for the Composition API. But that's the only way I was able to pull the data from the API.
If my solution is wrong, what method should it be, I'm new at Vuejs can you help?
You need to return the variables from the setup function so that they can be accessed from within the template.
If setup returns an object, the properties on the object can be
accessed in the component's template, as well as the properties of the
props passed into setup:
setup() {
let data = ref([]);
axios
.get("https://api.coindesk.com/v1/bpi/currentprice.json")
.then((res) => {
data.value = res.data.bpi;
});
// return the data as an object
return {
data
}
}
Read more about this in the official vue doc
You can create api dir inside src folder and then inside api dir create a file api.ts and put this code
export async function callApi(endpoint :string, method :string){
return await fetch(endpoint,{
method:method,
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}).then(async response => {
const resData = await response.json()
if (!response.ok) {
// do something to determine request is not okay
resData.isSuccess = false
}
return resData
}).catch(error => {
console.log("callApi in api.ts err")
console.log(error)
throw error
})
}
Go to you component and use this code
<template>
<div v-for="(item,i) in data.records" v-bind:key="i">
{{ item.chartName}}
</div>
</template>
<script>
import {onMounted,reactive} from "vue"
import {callApi} from "#/api/api"
export default{
name:'MyComponent',
setup() {
const data = reactive({
records: [],
})
onMounted( async() =>{
getRecords()
})
const getRecords = async() => {
let resData = await callApi('https://api.coindesk.com/v1/bpi/currentprice.json', 'GET')
data.records = resData
}
return {
data,
}
}
}
</script>
enter code here

Missing Dependency: aws-sdk in ./node_modules/node-pre-gyp/lib/info.js

I have a new Vue/Electron app just built using vue-cli-plugin-electron-builder and which will utilize sqlite.
The base install runs fine in development until I run yarn add sqlite3. I'm then presented with the aws-sdk missing dependency error.
Research suggests it's a webpack issue that can be fixed using webpack externals.
And, from the vue-electron-builder docs a similar explanation and fix.
I've updated my vue.config.js and webpack.config.js files based on this but am a few hours in now without resolution.
Any help or suggestions appreciated. Thanks.
[webpack node externals thread on github] (https://github.com/liady/webpack-node-externals)
Reading on webpack with backend apps
// vue.config.js
module.exports = {
pluginOptions: {
electronBuilder: {
// List native deps here if they don't work
externals: [ 'sqlite3' ],
},
// If you are using Yarn Workspaces, you may have multiple node_modules folders
// List them all here so that VCP Electron Builder can find them
nodeModulesPath: ['../../node_modules', './node_modules']
}
}
//webpack.config.js
// this file is for cases where we need to access the
// webpack config as a file when using CLI commands.
const nodeExternals = require('webpack-node-externals');
let service = process.VUE_CLI_SERVICE
if (!service || process.env.VUE_CLI_API_MODE) {
const Service = require('./lib/Service')
service = new Service(process.env.VUE_CLI_CONTEXT || process.cwd())
service.init(process.env.VUE_CLI_MODE || process.env.NODE_ENV)
}
module.exports = {
service.resolveWebpackConfig(),
externalsPresets: { node: true }, // in order to ignore built-in modules like path, fs, etc.
externals: [nodeExternals()], // in order to ignore all modules in node_modules folder
}
//package.json
{
"name": "spectral",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"electron:build": "vue-cli-service electron:build",
"electron:serve": "vue-cli-service electron:serve",
"postinstall": "electron-builder install-app-deps",
"postuninstall": "electron-builder install-app-deps"
},
"main": "background.js",
"dependencies": {
"axios": "^0.21.1",
"core-js": "^3.6.5",
"sqlite3": "^5.0.0",
"vue": "^2.6.11",
"vue-router": "^3.2.0",
"webpack-node-externals": "^2.5.2"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^4.5.0",
"#vue/cli-plugin-eslint": "^4.5.0",
"#vue/cli-plugin-router": "^4.5.9",
"#vue/cli-service": "^4.5.0",
"babel-eslint": "^10.1.0",
"electron": "^9.0.0",
"electron-devtools-installer": "^3.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"vue-cli-plugin-electron-builder": "^2.0.0-rc.5",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}
//sqlite connection setup
const path = require('path');
const sqlite3 = require('sqlite3').verbose()
const dbPath = path.resolve('src/db/spectral.db');
let db
export const conn = () => {
if (!db || !db.open) {
db = new sqlite3.Database(dbPath)
}
return db
}
More research led me to this thread which solved the 'sqlite3 not defined error' but created a new error 'require not found' which required adding nodeIntegration = true into vue.config.js.
// working solution vue.config.js
module.exports = {
pluginOptions: {
electronBuilder: {
externals: ['sqlite3'],
nodeIntegration: true
},
}
};
Additional references
vue-electron-builder native modules

worker-loader doesn't work properly after restart

I'm trying to use web with vue-cli project.
My worker is in file user.worker.js. When I run vue-cli-service serve for first time it works, but after restart webpack tries to load user.worker.worker.js and cant because such file doesn't exist. If I rename or move the file it works for first time but after restart fails again.
App.vue
<template>
<div id="app"></div>
</template>
<script>
import Worker from "#/user.worker";
export default {
name: "App",
created() {
const inst = new Worker();
inst.postMessage({
path: `some data`,
});
},
};
</script>
user.worker.js
onmessage = async ({ path }) => {
postMessage({ path });
};
vue.config.js
module.exports = {
chainWebpack: (config) => {
config.module
.rule("worker")
.test(/\.worker\.js$/)
.use("worker-loader")
.loader("worker-loader")
.end();
},
};
package.json
"name": "worker-project",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.6.5",
"vue": "^2.6.11",
"worker-loader": "^3.0.3"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^4.5.0",
"#vue/cli-plugin-eslint": "^4.5.0",
"#vue/cli-service": "^4.5.0",
"babel-eslint": "^10.1.0",
"eslint": "^6.7.2",
"eslint-plugin-vue": "^6.2.2",
"vue-template-compiler": "^2.6.11"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"parserOptions": {
"parser": "babel-eslint"
},
"rules": {}
},
"browserslist": [
"> 1%",
"last 2 versions",
"not dead"
]
}

Additional loaders needed after installing Vuetify

Clean project built using latest VueCli, added Vuetify using vue add vuetify. Every thing works, added authentication script with i have used 3 times this year successfully i now get this error
ERROR Failed to compile with 1 errors 7:26:18 PM
error in ./src/auth/authService.js
Module parse failed: Unexpected token (18:10)
File was processed with these loaders:
* ./node_modules/eslint-loader/index.js
You may need an additional loader to handle the result of these loaders.
|
| class AuthService extends EventEmitter {
> idToken = null;
| profile = null;
| tokenExpiry = null;
# ./src/router.js 6:0-38 42:52-56 46:2-6
# ./src/main.js
# multi (webpack)-dev-server/client?http://192.168.0.15:3000/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
Stumped, been at this all day with no joy. Is that i need additional processing or config? Is so i can see what.
Any help?
Many thanks
Rolling pack npm packages, deleting Node_modules (getting desperate), reading everything i can find
/auth/authService.js
const localStorageKey = "loggedIn";
const loginEvent = "loginEvent";
class AuthService extends EventEmitter {
idToken = null;
profile = null;
tokenExpiry = null;
login(customState) {
webAuth.authorize({
appState: customState,
});
}
vue.config.js
const webpack = require("webpack");
module.exports = {
devServer: {
port: 3000
},
configureWebpack: {
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jquery",
"window.jQuery": "jquery",
jQuery: "jquery"
})
]
}
};
.eslint.js
module.exports = {
root: true,
env: {
node: true
},
extends: ["plugin:vue/essential", "eslint:recommended", "#vue/prettier"],
rules: {
"no-console": process.env.NODE_ENV === "production" ? "error" : "off",
"no-debugger": process.env.NODE_ENV === "production" ? "error" : "off",
"comma-dangle": [
"error",
{
arrays: "only-multiline",
objects: "only-multiline",
imports: "only-multiline",
exports: "only-multiline",
functions: "ignore"
}
]
},
parserOptions: {
parser: "babel-eslint"
},
overrides: [
{
files: ["**/__tests__/*.{j,t}s?(x)"],
env: {
mocha: true
}
}
]
};
package.json
{
"name": "admin-sept-2019",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint",
"test:unit": "vue-cli-service test:unit"
},
"dependencies": {
"auth0-js": "^9.11.3",
"core-js": "^2.6.5",
"vue": "^2.6.10",
"vue-router": "^3.0.3",
"vuetify": "^2.0.0",
"vuex": "^3.0.1"
},
"devDependencies": {
"#babel/plugin-transform-classes": "^7.5.5",
"#vue/cli-plugin-babel": "^3.11.0",
"#vue/cli-plugin-eslint": "^3.11.0",
"#vue/cli-plugin-unit-mocha": "^3.11.0",
"#vue/cli-service": "^3.11.0",
"#vue/eslint-config-prettier": "^5.0.0",
"#vue/test-utils": "1.0.0-beta.29",
"babel-eslint": "^10.0.1",
"chai": "^4.1.2",
"eslint": "^5.16.0",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-vue": "^5.0.0",
"node-sass": "^4.9.0",
"prettier": "^1.18.2",
"sass": "^1.17.4",
"sass-loader": "^7.1.0",
"vue-cli-plugin-vuetify": "^0.6.3",
"vue-template-compiler": "^2.6.10",
"vuetify-loader": "^1.2.2"
}
}
npm run serve will build my vue app

npm run build generates more files than just bundle.js bundle.css

I'm working on a SPA with Vue.js and Django.
I run npm run build to generate the bundle files that will be used in production. I was expecting to only generate two files: dist/bundle.js and dist/bundle.css. However, besides the aforemetnioned files, a third js file is also being generated: dist/js/about.add8abe8.js.
Why is this?
In my Django project, inside the frontend/src/views/ directory I have 3 Vue components: Home.vue, List.vue and About.vue.
EDIT:
I don't have a webpack.config file. But these are some other files that may be relevant:
package.json:
{
"name": "frontend",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"bootstrap": "^4.3.1",
"bootstrap-vue": "^2.0.0-rc.19",
"core-js": "^2.6.5",
"vue": "^2.6.10",
"vue-router": "^3.0.3"
},
"devDependencies": {
"#vue/cli-plugin-babel": "^3.7.0",
"#vue/cli-plugin-eslint": "^3.7.0",
"#vue/cli-service": "^3.7.0",
"#vue/eslint-config-prettier": "^4.0.1",
"babel-eslint": "^10.0.1",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.0.0",
"vue-template-compiler": "^2.5.21",
"webpack-bundle-tracker": "^0.4.2-beta"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"#vue/prettier"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions"
]
}
vue.config:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
// on Windows you might want to set publicPath: "http://127.0.0.1:8080/"
publicPath: "http://0.0.0.0:8080/",
outputDir: "./dist/",
chainWebpack: config => {
config
.plugin("BundleTracker")
.use(BundleTracker, [{ filename: "./webpack-stats.json" }]);
config.output.filename("bundle.js");
config.optimization.splitChunks(false);
config.resolve.alias.set("__STATIC__", "static");
config.devServer
.hotOnly(true)
.watchOptions({ poll: 1000 })
.https(false)
.disableHostCheck(true)
.headers({ "Access-Control-Allow-Origin": ["*"] });
},
// uncomment before executing 'npm run build'
css: {
extract: {
filename: "bundle.css",
chunkFilename: "bundle.css"
}
}
};