restify js default root page - javascript

I'm trying to write restful application using node.js restify. Here is my application's code :
var restify = require('restify');
var server = restify.createServer();
server.get(/.*/, restify.serveStatic({
directory: 'content',
default: 'index.html'
}));
server.listen(3000, function() {
console.log('%s listening at %s', server.name, server.url);
});
So, I can access index.html only by http://localhost:3000/index.html.
I also expect to see my index.html page on the root url, http://localhost:3000/ but now i'm receiving there
{"code":"ResourceNotFound","message":"/"}

Give this a try:
server.get(/\//, restify.serveStatic({
directory: './content',
default: 'index.html'
}));

Related

404 - File or directory not found in Next JS

I am making a next js application.
Deployment works fine in vercel.
For deploying the same project in another server, got help from https://stackoverflow.com/a/63660079/13270726 and used the same instructions in our app.
Deployed the out directory into server using ftp client.
Issue
-> When we enter into http://your-domain.com , it works fine. (Even page refresh also works fine in this page)
-> If we move to about page using the url, http://your-domain.com/about then it also works but on page refresh in the url http://your-domain.com/about results in the error,
-> This page refresh also results in the console error like,
Get http://your-domain.com/about Not found
next.config.js: (With public path)
const config = {
webpack: (config, { isServer }) => {
.
.
.
config.devServer = {
historyApiFallback: true
}
config.output.publicPath = "/"
return config;
}
}
module.exports = withPlugins(config);
The issue arises in page refresh only or when we manually type the url.. But while we navigate to it first time then the issue is not there.
Any good help would be much appreciated as I am stuck for long time..
Edit:
I have a server.js file and its code look like,
const dotenv = require("dotenv");
// import ENVs from ".env.local" and append to process
dotenv.config({ path: ".env.local" });
const express = require("express");
const address = require("address");
const chalk = require("chalk");
// create express web server instance
const app = express();
// pull out ENVs from process
const { LOCALHOST, PORT } = process.env;
// get the Local IP address
const LOCALIP = address.ip();
// tell express to serve up production assets from the out directory
app.use(express.static("out" + '/'));
app.get('/*', (req, res) => {
res.send('ok')
});
app.all('*', function(req, res) {
res.redirect('/index.html');
});
// tell express to listen for incoming connections on the specified PORT
app.listen(PORT, (err) => {
if (!err) {
// log the LOCALHOST and LOCALIP addresses where the app is running
console.log(
`\n${chalk.rgb(7, 54, 66).bgRgb(38, 139, 210)(" I ")} ${chalk.blue(
"Application is running at"
)} ${chalk.rgb(235, 220, 52).bold(LOCALHOST)} ${chalk.blue(
"or"
)} ${chalk.rgb(235, 220, 52).bold(`http://${LOCALIP}:${PORT}`)}\n`
);
} else {
console.err(`\nUnable to start server: ${err}`);
}
});

Share files with socket.io

I am using Node.js and Socket.io for my web application.
I want to broadcast a file which can be somehow large (>15 Mb)to all the connected sockets and then use it in my clients. Is there a way to do this?
PS: if you can have a demo with babylon.js + socket.io that would be awesome
EDIT:
As requested, my server code:
import { createServer } from 'http';
import { createSocketServer} from "./socket";
import cookieParser from "cookie-parser";
import express from "express";
import morgan from "morgan";
import path from "path";
const port = 3000;
// Create a new express application instance
const app: express.Application = express();
app.use(cookieParser());
app.use(morgan('dev'));
const server = createServer(app);
// create a socket.io server
createSocketServer(server);
app.use('/', express.static(path.join(__dirname, 'public')));
server.listen(port,'0.0.0.0', function () {
console.log('Server is listening on port ' + port + ' !');
});
Babylon Assets Loading code:
this.assetsManager = new BABYLON.AssetsManager(this.scene);
this.assetsManager.addMeshTask('obj task', '',
'http://192.168.0.100:3000/babylon-files/dir1/', 'objectFile.obj');
this.assetsManager.addMeshTask('mtl task', '',
'http://192.168.0.100:3000/babylon-files/dir1/', 'materialFile.mtl');
this.assetsManager.addTextureTask('text1 task',
'http://192.168.0.100:3000/babylon-files/dir1/texture1.jpg');
this.assetsManager.addTextureTask('text2 task',
'http://192.168.0.100:3000/babylon-files/dir1/texture2.jpg');
this.assetsManager.onFinish = ((tasks) => {
this.engine.runRenderLoop(() => {
this.scene.render();
});
}).bind(this);
this.assetsManager.load();
You sould store the *.obj & *.mtl files on the same server.
Note that your node & webserver code cant run on the same port.
You should use a reverse proxy or listen on diffrent ports.
This prevents cross site issues.
For example: create in your webserver a directory that is public accessable: http://example.com/assets/babylon-files
In your node code you can now trigger clients to load files from that path:
// socket.io logic above
// waiting for connetions, auth, etc...
// tell conencted clients what the should load from
// http://example.com/assets/babylon-files
socket.broadcast.emit('loadAsset', 'house.obj');
socket.broadcast.emit('loadAsset', 'car.obj');
socket.broadcast.emit('loadAsset', 'wall.obj');
The client should looks something like this:
// listen for socket.io events from server here
io.on("loadAsset", (filename) => {
// tell babylon to load assets
BABYLON.SceneLoader.Load("/assets/babylon-files", filename, engine, function (scene) {
// do something with the scene
});
// - or -
// tell babylon to append assets
BABYLON.SceneLoader.Append("/assets/babylon-files", filename, function (scene) {
// do something with the scene
});
});
On the same way you can send binary data to the clients:
fs.readFile("/path/to/obj<or>mtl/file", (err, buff) => {
if (err) {
res.status(500).end();
return;
}
socket.binary(true).emit("loadAsset", buff);
});

Ui-router refresh issue

I have configured my ui-router like this:
app.config(function($stateProvider, $urlRouterProvider, $locationProvider) {
$stateProvider
.state('home', {
url: "/home",
templateUrl : 'home/home.html',
controllerUrl: 'home/controller.js'
})
.state('blog', {
url: "/blog",
templateUrl : 'blogger/blog.html',
controllerUrl: 'bloger/controller.js'
})
$locationProvider.html5Mode({
enabled: true,
requireBase: true
});
});
Server code :
var express = require('express');
var serveStatic = require('serve-static');
var server_port = 9000;
var server_ip_address = '127.0.0.1'
var app = express();
app.use(express.static('app'));
app.use(serveStatic('app', {'index': ['index.html', 'index.htm']}));
dirName = 'app';
options = {
root: dirName,
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
app.get('*', function(req, res) {
return res.sendFile('index.html', options);
});
app.listen(server_port, server_ip_address, function () {
console.log( "Listening on " + server_ip_address + ", server_port " + server_port)
});
But whenever I hit Ctrl/Command + R (or refresh), it says that it cannot find the path? How can I get around this problem?
Folder structure : Views : ./app/home/, app/blog/ Basefile:
./app/index.html Angular UI-routing from : ./app/base.js
The problem would be in the server settings. Angular is Front Controller application. You need every request redirect to index.html/index.php on your server. Htaccess settings in apache for example. Further information can be found here: htaccess redirect for Angular routes
The Problem is from your server side you should handle all routes in your server.js file.
For Example here is the snippet
router = settings.express.Router()
dirName = settings.path.resolve(__dirname, '..', '..');
options = {
root: dirName + '/website/views',
dotfiles: 'deny',
headers: {
'x-timestamp': Date.now(),
'x-sent': true
}
};
router.get('*', function(req, res) {
return res.sendFile('index.html', options);
});
You can Use the below code in your app.js, & then it work :
UPDATED :
/** Below code set the html as your default engine*/
var fs = require('fs');
app.engine('html',function(path,opt,fn){ //manishp
fs.readFile(path,'utf-8',function(err,str){
if(err) return str;
return fn(null,str);
});
});
app.get('*',function(req,res){
res.render('<your_layout_file_or_basefile>');
});
This is mainly because your AngularJS routes aren't actual html pages. An example would be if you have a route in your angular app to /login. This url works fine if you link to it from inside your app but if a user tries to go directly to that page the server will return a 404.
This is because AngularJS HTML5 mode uses the History API to push a new url to your browser. Yes, this require some extra work on the server side to have those url return the correct content.

gulp browser-sync not serving json files

I have an issue where i am not able to serve json files from my sub-folders. Below is the code:
var browserSync = require('browser-sync').create();
// Static server
gulp.task('connect', function() {
browserSync.init({
server: {
baseDir: "app/"
}
});
});
All my static and angularjs files reside inside app folder. When i navigate to http://localhost:3000, the page loads but the corresponding json file inside app/data/myfile.json does not load.
I get the below error in my console:
POST http://localhost:3000/data/json/myfile.json 404 (Not Found)
The strange thing is when i try to load the path in my browser, the json file loads.
At first I used this way https://www.browsersync.io/docs/options/#option-serveStatic FAIL.
But
const ASSET_EXTENSION_REGEX = new RegExp(`\\b(?!\\?)\\.(${config.assetExtensions.join('|')})\\b(?!\\.)`, 'i');
const DEFAULT_FILE = 'index.html';
...
server: {
baseDir: './build',
middleware: function(req, res, next) {
let fileHref = url.parse(req.url).href;
if ( !ASSET_EXTENSION_REGEX.test(fileHref) ) {
req.url = '/' + DEFAULT_FILE;
}
return next();
}
}
...
config = {assetExtensions: [
'js',
'css',
'png',
'jpe?g',
'gif',
'svg',
'eot',
'otf',
'ttc',
'ttf',
'json',
'woff2?' ]}
SUCCESS

Using Morgan and Winston for logging - files are being generated but are blank

Here is my code:
var logDirectory = __dirname + '/log';
//ensure log directory exists
fs.existsSync(logDirectory) || fs.mkdirSync(logDirectory);
//create a rotating write stream
var accessLogStream = FileStreamRotator.getStream({
filename: logDirectory + '/access-%DATE%.log',
frequency: 'daily',
verbose: false
})
// setup the logger
//app.use(morgan('combined', {stream: accessLogStream}))
app.use(morgan('combined', {stream: logger.stream}))
/*********************************************************************/
//This is 404 for API requests - UI/View 404s should be
//handled in Angular
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
app.set('port', 5050);
var server = app.listen(app.get('port'), function () {
//debug('Express server listening on port ' + server.address().port);
console.log('Express server listening on port ' + server.address().port);
});
All the necessary dependencies are being reference and the code references a logger.js file which includes the following code:
var winston = require('winston');
winston.emitErrs = true;
var logger = new winston.Logger({
transports: [
new winston.transports.File({
level: 'info',
filename: './logs/all-logs.log',
handleExceptions: true,
json: true,
maxsize: 5242880, //5MB
maxFiles: 5,
colorize: false
}),
new winston.transports.Console({
level: 'debug',
handleExceptions: true,
json: false,
colorize: true
})
],
exitOnError: false
});
module.exports = logger;
module.exports.stream = {
write: function(message, encoding){
logger.info(message);
}
};
Files are being generated and the file names are timestamped.
Why do my log files have nothing in them?
in place of
app.use(morgan('combined', {stream: logger.stream}))
try using
app.use(morgan('default', { 'stream': logger.stream}));
This should just write the resource and requested and the Browser Info along with a timstamp to your all-logs.log file.
The winston.log won't use your transports
logger.info('test'); will log test to both the console and the file since those are your defined transports.
Is your 'logger' located in a separate .js file or the same as your express server?
Here is my full logger.js file that I use in my express implementations:
https://gist.github.com/pbaio/ac934a06b91b99be6526
I would put that in a separate file in your parent directory such that you would reference it in your server file as such:
var logger= require('..logger.js');
then I would incorporate it as you do now in your middle:
app.use(morgan('combined', {stream: logger.stream}));
I would also delete your logs directory and have the app stop creating the directory all together, then I would recreate the log directory manually
I would imagine that should remedy your entire issue

Categories

Resources