Can't connect to my WebSocket from within my Angular2 app - javascript

Hej there.
I have a app using Node.js/Electron/Angular2 (TypeScript). Using socket.io I created a WebSocket. Everything works fine, as long as I'm not inside my Angular2 app.
I tried the whole day to get this running, without luck. I downloaded a working tutorial, but can't find the missing link. Drives me crazy!
This is my electron.js starting the app, creating the websocket server side
This is my index.html with working websocket, but as native JavaScript code
This is my root component of Angular2 trying to get the websocket running
The error - wich does not stop the compilation - I get, is root.component.ts(14,17): error TS2304: Cannot find name 'io'..
How can I get rid of that error? Or better: What's the best practice for this websocket communication inside Angular2?
Thanks in advance.

Now I solved this issue this way:
Installed socket.io-client typings $ tsd install socket.io-client and
added a typings reference to my main.ts file ///<reference path="../../typings/socket.io-client/socket.io-client.d.ts"/>.
Installed socket.io-client Node.js module $ npm install --save socket.io-client and
added this module to my index.html <script src="../node_modules/socket.io-client/socket.io.js"></script>
Now I can simply work with the socket inside any Angular2 component, without adding any extra lines.
socket = null;
constructor() {
this.socket = io('http://localhost:8181');
this.socket.on('news', function (data) {
console.log(data);
});
}
And for reference, this is my server socket code inside my main Electron .js file:
var server = require('http').createServer(function(req, res) {})
socket = require('socket.io')(server, {});
server.listen(8181);
socket.on('connection', function(socket) {
socket.emit('news', {hello: 'world'});
socket.on('my other event', function(data) {
console.log(data);
});
});
Hope this helps anyone later. Thank to Thierry Templier and dvlsg for the help.

I would note that if you're using electron that you shouldn't really consider electron.js to be server side. It's more of a client launcher / bootstrap, and must be running on each client. You'd have to have a separate node application (and I would strongly suggest it, in the case of socket.io) to truly make your code server side.
As for your question, you could try adding import io from 'socket.io-client' or var io = require('socket.io-client') in your root component (after you npm install socket.io-client, if necessary).

You need to install the socket.io typings (see this link: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/socket.io/socket.io.d.ts) using the command:
$ tsd install socket.io
Then you need import it:
import * as io from 'socket.io';

Related

Rendering react with node.js in development

I am (very) new to node.js and I am trying to get a development environment started with React.
const express = require('express')
const mongoose = require('mongoose')
const app = express()
// this displays the index.html file
app.use(express.static(__dirname + '/public'));
// trying to see the app.js
app.get('/', (req, res) => {
res.render('app')
})
app.listen(process.env.PORT || 5000);
Right now I am simply trying to be able to view my app.js when I run nodemon. But right now it is only showing the index.html file in the public folder. and when I run npm start it renders both the index.html and the app.js.
I am 100% doing something wrong and am not in my element here. Any help/advice would be appreciated.
My full repo is here for viewing here
Thank you in advance.
Your code is simply serving a static HTML file located in the public directory everytime the user make a GET request to the root (in your case, localhost:5000). It is not interacting with React yet.
Usually when starting a project with React (frontend) and Node (backend), you would create them as separate projects, in separate repositories.
So you could create a React application using a bootstrap such as create-react-app running on PORT 3000 and in another terminal tab, start your NodeJS application in PORT 5000 like in your example. Then, you can call your backend endpoint from your frontend React application, by referencing http://localhost:5000
By doing this, your backend code don't need to serve static files anymore, it can return data such as JSON and make connections to a database for example.
Since your question is not specific enough, you could be talking about server side render. In server side render apps using Node and React, you have a frontend built with React and a Node server that will return the same React code as a string, using the react-dom/server package to help. This is more complex, but basically you will have the same React code on the client AND on the server. There are performance benefits, because the user can see some content rendered right when he enters the page, without having to wait the React bundle (javascript file) to load. If you want to know more about creating a server side render app with React and Node, there is a nice digital ocean tutorial here
If you want to connect your react js project to the node js
In Development
you simply run their server and start it
In Production
You can use sendFile function coming from express.js to run the frontend
https://dev.to/loujaybee/using-create-react-app-with-express

Execute NPM module through cordova

I created an app using cordova and everything is fine, expect I need to use a node module which doesn't have a client-side equivalent because I'm dealing with file write streams etc. I have found Cordova hooks to be my best shot so far, where I create an app_run hook to execute a node file that runs a socket server to listen for events from the client side.
I know, a very longwinded solution, but seems logically correct to me, the issue is that when I do create the server, building the app through Visual Studio 2017, the app launches on my android phone, but VS hangs on the "deploy" stage. I guess that it has to do with the event chain, so I created an asynchronous script like this:
(async function () {
const server = require('http').createServer()
const io = require('socket.io')(server)
io.on('connection', function (socket) {
console.log('heyo')
socket.emit('hello world', 'hi')
})
server.listen(3000, function (err) {
if (err) throw err
console.log('listening on port 3000')
})
})();
but this doesn't seem to work either, somehow VS hangs on "deploy". If anyone can possibly guide me in the right direction, that would be highly appreciated.
PS: I know the title is off, but every time I use StackOverflow to get help with a particular attempt, I'm told to do it another way, so I'll leave it open.
If the goal is to use socket.io in your cordova app, there IS a JS client for the web that you need to use and you don't need to use npm for that, just add a link to your client js file in your index file. (should be in a "client" folder when you init socket.io via npm).
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io('http://localhost');
</script>
https://socket.io/docs/client-api/

LevelDOWN could not locate the bindings file when using electron.js under Windows 7

I created nodeJS server that uses levelDOWN module. So when I'm starting my server with node app.js everything is fine. I want to create electron desktop app that will use my app.js file. So I installed electron module and created electronApp.js file:
var app = require('electron').app;
app.on('ready', function(){
// start http server
var server = require(__dirname + "/app");
});
Now I'm trying to run my application electron electronApp.js but I'm getting next error:
I tried node-gyp rebuild and electron-rebuild as well but it did not help. I'm dissapointed. How to solve it?
I met the same error and submitted an issue on Electron issue list: https://github.com/electron/electron/issues/8161
Hope this can be resolved soon.

How to use sql-injection package in Node.js application?

I want to prevent my app for SQL-Injection attack in Node.js,for that i am using sql-inection package of NPM.
My app.js File
var app = express();
var sqlinjection = require('sql-injection');
app.use(sqlinjection);
With this configuration i am directly sending request to server.
But with each request to the server the api does not send any response and gives no error or Warning.
I am using this Npm package sql injection npm js
Please guide me to how to use sql-injection in node.js and express.js project.
Thanks.
Please include following lines in your app.js file
app.use('/wordcloud',wordcloud);
app.use('/profanityfilter',profanityfilter);
app.use('/api/notification',notification);
app.use('/api/badge',badgecount);
app.use('/api/csrf',csrfRoute);
app.use(sqlinjection);
After requiring the npm package you must use this sql-injection package at the end of all your router.
and it will work fine.

Express + socket.io: socket.io client script is 404

This is driving me crazy... while I have a working version of Express + Socket.io, I can't seem to reproduce it with out-of-the-box NPM installs in a new project folder. Can anyone point out what I'm missing...? Here's my process:
I create a node_modules folder in my project directory (pwd), then do:
npm install express
npm install socket.io
Running those two commands puts the packages in my project's node_modules folder as expected. Now I set up my server with the following:
var express = require('express'),
server = express.createServer().use( express.static(__dirname+'./public') ).listen( 8080 ),
io = require('socket.io').listen(server);
My public folder contains static assets for my application. My public index HTML page includes a script tag for:
<script src="/socket.io/socket.io.js"></script>
Finally, I run my server script and go to the application in a web browser. My static public files are all served properly, however I get a 404 for /socket.io/socket.io.js. Now, I can swap in an express package from another old project and have this whole system work. Somehow that package instance is configured differently, but I can't figure out how to reproduce that. The Express website mentions something about installing dependencies, although running npm install -d doesn't seem to help (is there a specific pwd that I need to be in while running npm install -d?). I figure I must be missing something important about configuring a new Express instance after installing it with NPM.
Thanks for any and all insight!
Okay, so my example was actually an abbreviation of my code, and that example code does actually work. My real code with problems was a bit more cluttered, like so:
var server = express.createServer();
server
.use( server.router )
.use( express.static(__dirname+'/../public') )
.get('/api', function(req, res) {
res.write('API');
});
server.listen(8080);
var io = require('socket.io').listen(server);
I fixed the above code by doing the following:
server = server.listen(8080);
Apparently the listen command wraps the server object with some additional functionality. My originally posted shorthand example actually does work because listen is chained onto the final return into the server variable. Interesting little nuance.

Categories