This is my first attempt at using Socket.io
I'm creating an api to emit some data. It work's fine.
Here is the code I think needs to be modified :
app.use(express.static(__dirname + '/node_modules'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
res.setHeader('Access-Control-Allow-Origin', '*');
});
In reference to the above code, the data is being successfully emitted to the index.html file. The port I have used is 4200. So if I enter localhost:4200 in the browser I'm able to see the data being displayed in the index.html file. Now I want to use localhost:4200 in my angular js project to get the data but instead I get the html contents of the index.html file.
Here is the snippet from my angularjs code:
setInterval(function(){
$http.get("localhost:4200").success(function(response) {
console.log(response);
})
}, 500);
What I'm I doing wrong here?
I was able to get it to work by adding the following angular snippet :
$scope.server = "100.20.32.20"; //Ip of my machine
$scope.socket = io('http://' + server + ':4200');
socket.on('broad', function(data) {
console.log($scope.data);});
Related
This error started showing herself after I added $locationProvider.html5Mode(true) to my state config on AngularJS:
'Cannot GET error' after refreshing page with html5mode
I`ve searched for it and found this fix to server side but it doesn't work either because of some JSON errors:( Maybe someone know how to properly fix it witout making new errors?)
app.get('*', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
Try changing your code to the below:
app.all('/*', function(req, res) {
res.sendFile('index.html', { root: __dirname + '/public/index.html' });
});
I am a newbie of angularjs. My version is 1.6.4 using with nodeJS. I am following this tutorial for file upload leon/angular-upload. I did all the steps written here to make it work which are.
1) bower install --save angular-upload
2) Add module dependency "lr.upload" which i did
angular.module(__appName, ["ngMap", "multipleSelect", "lr.upload"]);
3) Add this code snippet in html page, so i did in my fileupload.html.
<div class="btn btn-primary btn-upload"
upload-button
url="/upload"
on-success="onSuccess(response)"
on-error="onError(response)">Upload</div>
4) And finally add script to html page.
<script src='bower_components/angular-upload/angular-upload.min.js'></script>
But i am still getting error:
POST http://localhost:3000/upload 404 (Not Found)
My server.js is code is:
var express = require("express");
var app = express();
app.use(express.static(__dirname + '/app'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get("/", function(req, res){
res.redirect("app/index.html");
});
app.listen(3000, function(){
console.log("Tellworld web app listening on port 3000");
})
Here is Server.JS files that you should follow
https://github.com/leon/angular-upload/blob/master/example/server.js
You have to add :
app.post('/upload', function(req, res) { /*do your post processing here */ })
Your server will also need it route that receive request from the angular's route directive. In clear english you will need to declare a route pointing to upload in your server which may look like the code below
app.post('/upload', function(req, res){
console.log(req.body); //this is just to show the request body on your console
});
I'm currently developing game app. I have started with authorization via FB and now i got stuck on connecting front-end angular with back-end node.
My folder contains 2 subfolders without any connections or dependencies between them: client and server.
Client contains scaffolded yeoman application based on angular generator so that my front end is fired with grunt serve. I'm using here angular-socket-io by btford.
Server contains nothing but basic server allowing to connect and loggs to console when someone will connect via socket.io.
My problem lies on client folder, front-end part, where:
angular.module('battleshipsApp')
.factory('socket', function (socketFactory) {
var myIoSocket = io.connect('http://localhost:5432');
var mySocket = socketFactory({
ioSocket: myIoSocket
});
return mySocket;
});
doesn't work.
I think i linked everything i needed:
src="bower_components/angular-socket-io/socket.js"
<!-- endbower -->
<!-- endbuild -->
src="bower_components/angular-socket-io/mock/socket-io.js"
Here my simple server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
var logIn = new Date();
console.log(logIn + ' user connected')
socket.on('disconnect', function() {
var logOut = new Date();
console.log(logOut + ' bye bye')
})
});
http.listen(5432, function(){
console.log('listening on localhost:5432');
});
And I can't figure out why these two cannot connect.
I couldn't find any answers which could fit my problem in google.
I'm looking right now on both terminals, one with grunt serve in action and one with nodemon server.js and no errors, no connections.
Also there are no errors on dev tools console in chrome on front-end side.
Any help? Or maybe approach for this app with my structure is bad?
I guess you need to add to your server :
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
next();
});
I cant get my mind straight about routing of api calls with angularjs and express(ie nodejs). I set up the routing in my server as below:
require('./app/routes')(appExpress, passport);
I will have three collections in my database. I need to set upp calls to the api for all the collections in my routes file as below:
module.exports = function(app, passport) {
app.get('/api/compititions', function(req, res) {
Comps.find(function(err, comps) {
console.log(comps);
if (err)
res.send(err);
res.json(comps);
});
});
app.get('/api/swimers', function(req, res) {
// Add code to do something
});
app.post('/api/swimers', function(req, res) {
// Add code to do something
});
// all other calls
app.get('*', function(req, res) {
// send the rest of the calls to the app
});
}
The problem is that adding calls and code for 15 ish calls will become a very LONG file. I would like to separate these calls to different files or in some way make this file readable. Is that good practice or am I on the wrong path?
Thanks for the help and guidance!
I am using Node.JS with Express, Angular.JS and the node module connect-roles for ACL. I want to allow a user with user.status of "Platinum" to access "Platinum" but not "Gold" and vice versa.
I have the ACL part working, if I enter /Platinum into the navigation bar I can't access /Gold, but when I try to access /Platinum I only get the template but not the root shell, so what comes up is this:
You made it!
You have the {{status}} status!
If I click on a link in angular to /Platinum, everything works as it should. If I enter any neutral address in the navigation bar, everything works as it should.
This should be an easy fix, but I've not figured it out.
Here is the code that sets up authorizations, I'm pretty sure everything here is okay.
ConnectRoles = require('connect-roles')
var user = new ConnectRoles({
failureHandler: function(req, res, action){
var accept = req.headers.accept || '';
res.status(403);
if(accept.indexOf('html')) {
res.render('access-denied', {action: action});
} else {
res.send('Access Denied - You don\'t have permission to: ' + action);
}
}
});
var app = express();
app.use(user.middleware());
// Setting up user authorizations,
// i.e. if req.user.status = "Platinum", they are given Platinum status
user.use('Platinum', function(req) {
if (req.user.status == 'Platinum') {
return true;
}
});
user.use('Gold', function(req) {
if (req.user.status == 'Gold') {
return true;
}
});
user.use('Admin', function(req) {
if (req.user.status == 'Admin') {
return true;
}
});
That sets up authorizations, now the problem lies below with the routing.
app.post('/login', passport.authenticate('local',
{ successRedirect: '/', failureRedirect: '/login' }));
app.get('/Platinum', user.is('Platinum'), function(req, res) {
//Obviously the code below is wrong.
res.render('templates/support/Platinum');
});
app.get('/Gold', user.is('Gold'), function(req, res) {
res.render('templates/support/Gold');
});
The way you are configuring your routes on server side (using express) is not correct. For a single page app like AngularJS, you need to do all of the routing for pages on the client (i.e. in Angular). The server still defines routes for API requests (e.g. getting and posting data) and static resources (index.html, partial HTML files, images, javascript, fonts, etc), though.
Thus the following code is wrong in your server side JS:
app.get('/Platinum', user.is('Platinum'), function(req, res) {
//Obviously the code below is wrong.
res.render('templates/support/Platinum');
});
app.get('/Gold', user.is('Gold'), function(req, res) {
res.render('templates/support/Gold');
});
Just remove those lines.
Instead, you need to define the routes that the server will handle, such as your /login post one first, and how to get static files (I suggest prefixing them all with /pub in the URL). Then you need to do something like the technique in this answer to return your index.html page if no routes are matched.
That way, when a user types http://localhost:port/Gold, express will see there is no route defined for /Gold, so it will return index.html, which will load AngularJS, run your Angular app, which will then look at the URL and see if that matches any of the routes your AngularJS app has configured, and if so, fetch the partial for that page and insert it into your ng-view (if using the core router).