how do I connect to wss socket with vue-socket.io? - javascript

I am trying to connect with wss but wss keep replacing with https
My socket config is
import Vue from 'vue';
import VueSocketIO from 'vue-socket.io';
import * as io from 'socket.io-client';
import store from '../store';
export default async (/* { app, router, Vue ... } */) => {
Vue.use(new VueSocketIO({
debug: true,
connection: io('wss://echo.websocket.org'),
vuex: {
store,
actionPrefix: 'SOCKET_',
mutationPrefix: 'SOCKET_',
},
}));
};
I get below error :

Related

Vue Vite SPA application is not communicating with Laravel API GET http://localhost:5173/user/projects 404 (Not Found)

I'm trying to fetch a list from an endpoint but It throws error 404, It works from Postman but not inside the application. I created the .env file manually inside application root folder.
The error message shows GET http://localhost:5173/user/projects 404 (Not Found)
.env:
VUE_APP_API_URL=http://localhost:8000
VUE_APP_PUBLIC_PATH=/
src/services/api.js:
import axios from 'axios';
// eslint-disable-next-line no-undef
const api = axios.create({ baseURL: process.env.NODE_ENV.VUE_APP_API_URL });
export default api;
vite.config.ts:
import { defineConfig } from 'vite'
import vue from '#vitejs/plugin-vue'
import AutoImport from 'unplugin-auto-import/vite'
import VueRouter from 'unplugin-vue-router/vite'
import { VueRouterAutoImports } from 'unplugin-vue-router'
import Components from 'unplugin-vue-components/vite'
import { HeadlessUiResolver } from 'unplugin-vue-components/resolvers'
export default defineConfig({
plugins: [
VueRouter({}),
vue(),
Components({ resolvers: [HeadlessUiResolver()] }),
AutoImport({
imports: ['vue', '#vueuse/head', VueRouterAutoImports],
}),
],
server: {
open: true,
},
})
src/pages/Projects/index.vue:
async function listProjects() {
let projects = [];
let projectsResponse = '';
projectsResponse = await api.get('/user/projects');
if (projectsResponse) {
projects = projectsResponse.data.projects;
}
if (!projects || !projects.length) {
projects = [];
return;
}
projects = projects;
}
The endpoint is http://127.0.0.1:8000/user/projects, It works from postman (The backend is running locally)
Since you are using Vite, you should use import.meta.env instead of process.env to import environment variables. So you sould set the base url with: baseURL: import.meta.env.VUE_APP_API_URL.
See Vite documentation.
process.env.VUE_APP_API_URL is what you need to access the env variable you've defined.
import axios from 'axios';
// eslint-disable-next-line no-undef
const api = axios.create({ baseURL: process.env.VUE_APP_API_URL});
export default api;

I need to make the port number a variable that can be added from a dialog box in Vite js

I need to make the port number a variable that can be changed when a user enters the port number in a dialog box. So I already have a port number in here which it is 3080. I will have to make a dialog box or a modal in my front end that asks the user if they would like to change the port number in which it is running. This user will then be able to change the port number by the click of a button. I am using Vue 3 with Vite. But I cannot make this port number a state that can be changed. Does anyone know what to do?
Thank you to anyone reading this! Here is my vite.config.js file
import { defineConfig, loadEnv } from 'vite'
import vue from '#vitejs/plugin-vue'
export default defineConfig(({mode})=>{
const env = loadEnv(mode, process.cwd());
return{
plugins: [vue()],
build:{
outDir:"./wwwroot/app/", sourcemap:true
},
server: {
proxy: {
"^/api": {
target:env.VITE_PORT,
changeOrigin: true,
secure: false,
withCredentials: true,
rewrite: (path) => path.replace(/^\/api/, ``),
},
},
port:3080
},
}
})
This is my main.js file
import { createApp } from 'vue'
import VueApexCharts from "vue3-apexcharts";
import router from './router';
import App from './App.vue'
import store from './store';
import '#fortawesome/fontawesome-free/js/all';
import 'bootstrap/dist/css/bootstrap.min.css';
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import vClickOutside from "click-outside-vue3"
const app=createApp(App)
app.use(VueApexCharts);
app.use(router)
app.use(ElementPlus)
app.use(store)
app.use(vClickOutside)
app.mount('#app')

How do I set up GraphQL for my vuejs 3 app

I am new to VueJS and I have been trying to setup graphql with my vuejs but I can't seem to get it right.
Funny thing is there's no error on my console apart from a
[Vue warn]: A plugin must either be a function or an object with an "install" function. error.
And this only comes up when I instantiate vueapollo to the use method.
Here's my main.js file
import { createApp } from 'vue';
import ElementUI from 'element-plus';
import ApolloClient from 'apollo-client';
import { createHttpLink } from 'apollo-link-http';
import { InMemoryCache } from 'apollo-cache-inmemory';
import VueApollo from 'vue-apollo';
import App from './App.vue';
import router from './router';
import store from './store';
import './assets/style/theme/index.css';
// HTTP connection to the API
const httpLink = createHttpLink({
// You should use an absolute URL here
uri: 'http://localhost:4999/graphql',
});
// Cache implementation
const cache = new InMemoryCache();
// Create the apollo client
const apolloClient = new ApolloClient({
link: httpLink,
cache,
});
/* The provider holds the Apollo client instances
that can then be used by all the child components. */
// eslint-disable-next-line
const apolloProvider = new VueApollo({
defaultClient: apolloClient,
});
createApp(App)
.use(ElementUI)
.use(apolloClient)
.use(store)
.use(router)
.mount('#app');
I have a page file where presently, I want to reach the "Hello" endpoint I created earlier
<template>
<div>
<h1>Hello</h1>
<h1>{{ hello }}</h1>
</div>
</template>
<script>
import gql from 'graphql-tag';
export default {
data() {
return {
hello: '',
};
},
apollo: {
// Simple query that will update the 'hello' vue property
hello: gql`
query {
hello
}
`,
},
};
</script>
I also struggled with it a couple of weeks ago.
I don't remember how, but I got it to work.
I post my code here, in case it helps anyone in the future.
The difference between the question author and my code is how I pass the Apollo client to the create-app setup function. I don't know if it is correct, but it works.
PS: I am also using TypeScript on top of everything.
My apollo-client.ts file
import { ApolloError } from '#apollo/client';
import { ApolloClient, InMemoryCache, HttpLink } from '#apollo/client/core';
import { ErrorResponse } from '#apollo/client/link/error';
import { onError } from '#apollo/client/link/error';
import { logErrorMessages } from '#vue/apollo-util';
function getHeaders() {
const headers = {
'content-type': 'application/json',
};
/* const token = window.localStorage.getItem('apollo-token');
if (token) {
headers['Authorization'] = `Bearer ${token}`;
} */
return headers;
}
// Create an http link:
const httpLink = new HttpLink({
uri: 'http://localhost:3000/query',
fetch: (uri: RequestInfo, options: RequestInit) => {
options.headers = getHeaders();
return fetch(uri, options);
},
});
const errorLink = onError((error: ErrorResponse | ApolloError) => {
if (process.env.NODE_ENV !== 'production') {
logErrorMessages(error);
}
});
// Create the apollo client
export const apolloClient = new ApolloClient({
cache: new InMemoryCache(),
connectToDevTools: true,
link: errorLink.concat(httpLink),
});
My main.ts file:
import { apolloClient } from './apollo-client';
import { createApp, provide, h } from 'vue';
import { DefaultApolloClient } from '#vue/apollo-composable';
import { createApolloProvider } from '#vue/apollo-option';
import { loadFonts } from './plugins/webfontloader';
import App from './App.vue';
import router from './router';
import store from './store';
import vuetify from './plugins/vuetify';
// TODO: Auth
// import authPlugin from "./auth/authPlugin"
// Create a provider
const apolloProvider = createApolloProvider({
defaultClient: apolloClient,
});
loadFonts();
const app = createApp({
setup() {
provide(DefaultApolloClient, apolloClient);
},
render: () => h(App),
});
app.use(router).use(store).use(vuetify).use(apolloProvider).mount('#app');

Use socket.io with React

How do I use socket.io with React? I have this code for my client:
import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css"
const socket = io()
console.log(socket)
class App extends Component {
render() {
return (
// ...
)
}
}
export default App
And for my server:
const express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http)
io.on("connection", socket => {
console.log("New connection")
})
http.listen(8000, () => {
console.log("Started!")
})
But I keep getting this error:
POST http://localhost:3000/socket.io/?EIO=3&transport=polling&t=MdZyD8L 404 (Not Found)
What did I do wrong? Thanks.
PS: To launch the app, I do npm run start, and for the server node server/server.js
havn't really ran the code; but, did you notice the port in the error is 3000 rather than 8000 which you initialized the server to listen on?
reading https://socket.io/docs/client-api/, it says that the default is the window location, knowing react, you probably running on port 3000, which is the same 3000 in the error
try setting the port when initializing the socket object
const socket = io("localhost:8000");
Below is the code for connecting through socket if you want that after page is rendered then your socket get connected then write it in componentDidMount.
import React, { Component } from "react"
import io from "socket.io-client"
import "./App.css";
class App extends Component {
componentDidMount(){
let socket = io.connect("http://localhost:8000");
console.log(socket)
}
render() {
return (
// ...
)
}
}
export default App
For example you can go through the link :
https://medium.freecodecamp.org/how-to-create-a-realtime-app-using-socket-io-react-node-mongodb-a10c4a1ab676

Why is setting Vue.http for vue-resource ignored?

I'm using Vue.js 2.3.3, Vue Resource 1.3.3, Vue Router 2.5.3, and I'm trying to set up Vue-Auth. I keep getting a console error, however, that says auth.js?b7de:487 Error (#websanova/vue-auth): vue-resource.1.x.js : Vue.http must be set.. I'm setting Vue.http in main.js, but vue-resource is not picking it up for some reason.
main.js:
import Vue from 'vue'
import Actions from 'actions'
import App from './App'
Vue.use(Actions, {
locales: ['en', 'zh', 'fr']
})
Vue.http.options.root = 'https://api.example.com'
new Vue({
render: h => h(App),
watch: {
lang: function (val) {
Vue.config.lang = val
}
}
}).$mount('#app')
actions/index.js
import VueResource from 'vue-resource'
import Router from 'actions/router'
import I18n from 'actions/i18n'
export default {
install (Vue, options) {
Vue.use(Router)
Vue.use(I18n, options.locales)
Vue.use(require('#websanova/vue-auth'), {
router: require('#websanova/vue-auth/drivers/router/vue-router.2.x'),
auth: require('#websanova/vue-auth/drivers/auth/bearer'),
http: require('#websanova/vue-auth/drivers/http/vue-resource.1.x')
})
}
}
And if I add Vue.use(VueResource) to actions/index.js right below Vue.use(Router), I get a new error: Error (#websanova/vue-auth): vue-router.2.x.js : Vue.router must be set.
On the other hand, if I move Vue.http.options.root = 'https://api.example.com' to right below the import statements, I get yet another error: Uncaught TypeError: Cannot read property 'options' of undefined
You need to import 'vue-resource' in to your main.js file to get ride of this errors:
import Vue from 'vue'
import VueResource from 'vue-resource';
import Actions from 'actions'
import App from './App'
Vue.use(Actions, {
locales: ['en', 'zh', 'fr']
})
Vue.use(VueResource)
Vue.http.options.root = 'https://api.example.com'
new Vue({
render: h => h(App),
watch: {
lang: function (val) {
Vue.config.lang = val
}
}
}).$mount('#app')
Using axios and not vue-resource this is a working setup for me:
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueRouter)
Vue.use(VueAxios, axios)
Vue.router = new VueRouter({
// Your routes.
})
Vue.use(require('#websanova/vue-auth'), {
auth: require('#websanova/vue-auth/drivers/auth/bearer.js'),
http: require('#websanova/vue-auth/drivers/http/axios.1.x.js'),
router: require('#websanova/vue-auth/drivers/router/vue-router.2.x.js'),
})
App.router = Vue.router
new Vue(App).$mount('#app')
For more guidance you can refer to this great tutorial: https://codeburst.io/api-authentication-in-laravel-vue-spa-using-jwt-auth-d8251b3632e0

Categories