How to use socket.io to handle requests? - html

I am trying to use socket.io for handling requests between html page and http server I got Cannot POST / [HTTP/1.1 404 Not Found 1ms]
the server code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
console.log(__dirname);
app.use(express.static(__dirname+'/public'));
app.get('/', function(req, res){
res.sendfile(__dirname+'/public/registration.html');
});
io.on('connection', function(socket){
socket.on('registration',function(msg){
console.log('user data'+ msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
html page like the following
<html>
<head>
<script src="https://cdn.socket.io/socket.io-1.3.4.js">
var socket = io('http://localhost');
console.log(socket);
socket.emit('registration',"test");
</script>
</head>
<body>

Install node,
Create a folder for your app,
Create package.json file:
{
"name": "socket.io-test",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node server"
},
"dependencies": {
"express": "~4.13.1",
"socket.io": "^1.4.6"
}
}
Run npm install,
Create server.js - your original code pasted here:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
console.log(__dirname);
app.use(express.static(__dirname+'/public'));
app.get('/', function(req, res){
res.sendfile(__dirname+'/public/registration.html');
});
io.on('connection', function(socket){
socket.on('registration',function(msg){
console.log('user data'+ msg);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Create the /public folder in your working directory,
Create /public/registration.html file:
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io('http://localhost:3000');
socket.on('connect', function() {
socket.emit('registration',"test");
document.getElementById('socket').innerHTML='connected';
});
</script>
</head>
<body>
<h1>Testing socket.io with nodejs</h1>
<h3 id="socket"></h3>
</body>
</html>
Start the server with node server or npm start,
Go to localhost:3000 in your browser
It will work

Related

The following tasks did not complete: serve, sass. Did you forget to signal async completion?

Other answers were not helpful. I'm using Gulp 4 on Windows 10.
I get the following error when running 'gulp serve'
The following tasks did not complete: serve, sass
[18:48:51] Did you forget to signal async completion?
My gulpfile.js
var gulp = require('gulp');
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var reload = browserSync.reload;
gulp.task('sass', function() {
return sass('./public_html/lib/scss/main.scss')
.pipe(gulp.dest('./public_html/css'))
.pipe(reload({ stream:true }));
});
gulp.task('serve', gulp.series('sass', function() {
browserSync({
server: {
baseDir: 'public_html'
}
});
gulp.watch('lib/scss/*.scss', gulp.series('sass'));
}));
Try this instead:
gulp.task('sass', function() {
return gulp.src('./public_html/lib/sass/main.scss')
.pipe(sass()).on("error", sass.logError))
.pipe(gulp.dest('./public_html/css'))
.pipe(reload({ stream:true }));
});
Note you need gulp.src, then a call to sass.

angular not working with express after adding the files in the server

hello am having a problem with angular not working with express. I had the same problem earlier and it was because i did not add
app.use('/', express.static('../client/partials/javascripts'));
now i have
My server code is
var express = require('express');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var expressSession = require('express-session');
var mongoose = require('mongoose');
var hash = require('bcrypt-nodejs');
var path = require('path');
var passport = require('passport');
var localStrategy = require('passport-local' ).Strategy;
// mongoose
mongoose.connect('mongodb://localhost/mean-auth');
// user schema/model
var User = require('./models/user.js');
// create instance of express
var app = express();
// require routes
var routes = require('./routes/api.js');
// define middleware
app.use(express.static(path.join(__dirname, '../client')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('express-session')({
secret: 'keyboard cat',
resave: false,
saveUninitialized: false
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/', express.static('../client/partials/javascripts'));
app.use(express.static(path.join(__dirname, 'public')));
// configure passport
passport.use(new localStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());
// routes
app.use('/user/', routes);
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, '../client', 'index.html'));
});
app.get('/main', function(req, res) {
res.sendFile(path.join(__dirname, '../client/views', 'index.html'));
});
// error hndlers
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use(function(err, req, res) {
res.status(err.status || 500);
res.end(JSON.stringify({
message: err.message,
error: {}
}));
});
module.exports = app;
my angular code is
var app = angular.module('tiks', []);
app.controller('mainController', function($scope){
$scope.posts = [];
$scope.newPost = {created_by: '', text: '', create_at: ''};
$scope.post = function(){
$scope.newPost.created_at = Date.now();
$scope.posts.push($scope.newPost);
$scope.newPost = {created_by: '', text: '', created_at: ''};
};
});

Livereload of .html pages - Gulp

I have got this code so far, but it does not work.
var gulp = require('gulp'),
connect = require('gulp-connect');
gulp.task('webserver', function() {
connect.server({
livereload: true
});
});
gulp.task('default', ['webserver']);
You should specify file path to watch look this :
var gulp = require('gulp');
var connect = require('gulp-connect');
gulp.task('connect', function() {
connect.server({
root: 'app',
livereload: true
});
});
gulp.task('html', function () {
gulp.src('./app/*.html')
.pipe(connect.reload());
});
gulp.task('watch', function () {
gulp.watch(['./app/*.html'], ['html']);
});
gulp.task('default', ['connect', 'watch']);

Gulp - Unexpected character '#' (1:0) while parsing style\main.scss

I have gulp installed and this is the error that I get. Can someone help me out please?
I have tried deleting the node_modules and did the npm-install. But it still doesnt work.
This is how my gulpfile looks like.
var gulp = require('gulp');
var gutil = require('gulp-util');
var browserify = require('browserify');
var babelify = require('babelify');
var scssify = require('scssify');
var source = require('vinyl-source-stream');
var path = require('path');
var spawn = require('child_process').spawn;
var gls = require('gulp-live-server');
var commandLineArgs = require('command-line-args');
var sass = require('gulp-sass') ;
var notify = require("gulp-notify") ;
var bower = require('gulp-bower');
var runSequence = require('run-sequence');
var lodash = require('lodash');
var config = {
sassPath: './gssp/client/style',
bowerDir: './bower_components'
};
function onError(error) {
gutil.log(error.message);
console.log(error.toString());
}
var cli = commandLineArgs([
{ name: 'packages', alias: 'p', type: String, defaultValue: [""], multiple:true }
]);
var options = cli.parse();
gulp.task('bower', function() {
return bower()
.pipe(gulp.dest(config.bowerDir))
});
gulp.task('icons', function() {
return gulp.src(config.bowerDir + '/font-awesome/fonts/**.*')
.pipe(gulp.dest('./dist/fonts'));
});
gulp.task('embeddedIcons', function() {
return gulp.src('./gssp/src/leafs/icon/fonts/**.*')
.pipe(gulp.dest('./dist/src/leafs/icon/fonts'));
});
gulp.task('css',['bower'], function() {
return gulp.src(config.sassPath + '/*.scss')
.pipe(sass({
outputStyle: 'compressed',
includePaths: [
'./gssp/client/style',
config.bowerDir + '/bootstrap-sass/assets/stylesheets',
config.bowerDir + '/font-awesome/scss',
]
})
.on('error', sass.logError))
.pipe(gulp.dest('./dist/css'));
});
gulp.task('runLiveServer', function () {
var server = gls.new(['gssp/index.js', options.packages.join(" ")]);
server.start();
gulp.watch(['./core/**/*.js','./gssp/**/*.scss'], ['build']);
gulp.watch(['./dist/bundle.js'], function (file) {
server.notify.apply(server, [file]);
});
});
gulp.task('copyStatics', function() {
return gulp.src('./core/server/public/**/*.*')
.pipe(gulp.dest('./dist'));
});
gulp.task('build',['copyStatics', 'icons', 'embeddedIcons', 'css'], function () {
return browserify({
entries: './gssp/client/index.js',
extensions: ['.jsx', '.js'],
debug: true
})
.transform("babelify", {presets: ["es2015", "react", "stage-0"]})
.bundle()
.on('error', onError)
.pipe(source('bundle.js'))
.pipe(gulp.dest('./dist'));
});
gulp.task('run-wrapper', function(done) {
var server = spawn('node', ['serviceWrapper.js'], {stdio: ['inherit']});
server.stderr.on('data', function(data){
process.stderr.write(data);
});
server.stdout.on('data', function(data) {
process.stdout.write(data);
});
server.unref();
});
gulp.task('run', function(done) {
console.log(lodash.concat);
var child = spawn('node', lodash.union(['gssp/index.js'], options.packages), {stdio: ['inherit']});
child.stderr.on('data', function(data){
process.stderr.write(data);
});
child.stdout.on('data', function(data) {
process.stdout.write(data);
});
});
gulp.task('watch', function() {
gulp.watch('./gssp/src/**/*.{js,jsx}', ['build']);
gulp.watch('./gssp/src/**/*.scss', ['build']);
});
gulp.task('serve', function(done) {
runSequence('build', ['run-wrapper', 'runLiveServer'],done)
});
gulp.task('start', function(done) {
runSequence('build', ['run-wrapper', 'run'], done);
});
gulp.task('default', ['start']);
This is how my bower file looks like.
{
"name": "gssp-sales",
"main": "index.js",
"version": "0.6.0",
"authors": [
"Vamshi Gudipati"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
],
"dependencies": {
"bootstrap-sass": "bootstrap-sass-official#~3.3.6",
"font-awesome": "fontawesome#~4.5.0"
}
}
I have gulp installed and this is the error that I get. Can someone help me out please?
I have tried deleting the node_modules and did the npm-install. But it still doesnt work.
This is how my gulpfile looks like
Open up your font-awesome.css file in dist/css and see in the first block #font-face where the src is pointing to. Make sure it is pointing to the correct directory where you have extracted the font-awesome fonts and the error will go away.
For me I had to do something like this in my gulpfile:
gulp.task('build-fonts', function(){
return gulp.src(config.bowerDir + '/font-awesome/fonts')
.pipe(gulp.dest('./dist/fonts'));
})

how to upload a file using angular js and html only to my local path

I tried some code in tutorialpoint and other sites. while clicking upload button it's not storing to my local folder named fileUpload
js file:
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";//created local folder named as fileUpload in same path where this files or found.
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
html file :
<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="upload.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
please help me to solve this issue.