hi i'm trying to push code from my html file into my javascript file using buffers, toString, and readFileSync. I have a javacript file named index.js and a html file named index.html. This is the error on my site :
https://secret-ocean-5221.herokuapp.com/
This is my JS:
var fs = require('fs');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(fs.static(__dirname + '/public'));
app.get('/', function(request, response) {
var buf = new Buffer(fs.readFileSync("index.html"), "utf-8");
response.send(buf.toString);
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
my HTML simply says:
Welcome to my site.
You are not calling the toString method, only passing it in. Change to:
response.send(buf.toString());
Also, static is a property of express, not fs.
app.use(express.static(__dirname + '/public'));
With that, assuming your index.html file is in public, you don't need the fs.readFileSync at all.
It would also be more idiomatic to call readFile and use the node callback so it is non-blocking.
app.get('/', function(request, response, next) {
fs.readFile("index.html", function (err, fileBuffer) {
if (err) {
return next(err); // Tell express to handle errors
}
response.send(fileBuffer.toString());
});
});
I found the problem.
(1) I did not push my html file into my github repo
(2) My code was wrong here is the right code :
var express = require('express');
var fs = require('fs');
var app = express();
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.get('/', function(request, response) {
fs.readFile('index.html', function(err, data){
response.send(data.toString());
});
});
app.listen(app.get('port'), function() {
console.log("Node app is running at localhost:" + app.get('port'));
});
Related
I created a Glitch project and I want to upload files to it via user input. I am using express-fileupload and I followed the sample code from their docs to upload a file, but I keep getting an error. I think it might have to do with the directory I am using to move the file to. I have tried using '/app/views/uploads' and 'uploads/' as well as '/assets' (I used assets.js to do so) and I haven't been able to store the file. Here's my code:
var express = require('express');
var fileUpload= require('express-fileupload');
var app = express();
var assets = require("./assets");
app.use("/assets", assets);
app.use(express.static('views'));
app.use(fileUpload());
app.set('view engine', 'ejs');
app.set('views', 'views');
app.get("/", function (request, response) {
response.render('index');
});
app.get('/fileupload', function(req, res) {
res.render('upload');
});
app.post('/upload', function(req, res) {
var sample= req.files.sample;
sample.mv('/assets', function(err) {
if (err)
return res.status(500).send(err);
res.send('File uploaded!');
});
});
var listener = app.listen(process.env.PORT, function () {
console.log('SERVER STARTED ON PORT ' + listener.address().port);
});
The file is received succesfully, so the file not being there is not why I get errors.
I normally get this as the error:
{"errno":-13,"code":"EACCES","syscall":"open","path":"/assets"}
If you know where to upload the files to, please let me know. Any help would be very appreciated!
Thanks for help in advance. I am getting following state from my console See Server running console log. Below Snippet is my app.js code where express and node server running. If you see my socket code my console.log underneath socket connection is not showing in server logs. Socket is not listening my messages.
I have also upload my sample of code at github, here you can find that (github.com/ferozpuri/node-app) client socket code is in SocketController.js an Angular controller file.
Here is my app.js file code, As you can see console log for "Connection was made" never show. and same with socket console.
var express = require('express');
var http = require('http');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var engines = require('consolidate');
var routes = require('./routes');
var users = require('./routes/user');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', path.join(__dirname, 'views'));
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router);
app.get('/', routes.index);
app.get('/users', users.list);
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
/// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function (err, req, res, next) {
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function (err, req, res, next) {
res.render('error', {
message: err.message,
error: {}
});
});
io.on('connection', function (socket) {
console.log('A connection was made!');
socket.on('chat.message', function (message) {
console.log('New Message : ' + message);
});
});
module.exports = app;
I am not getting socket response from node server. PLease let me know if i not explain this properly or any thing is not here.
Server listing on port you can see this in screenshort or my project structure
Project structure & app listening port OR NPM START CODE
You have set up all handlers but you did not initialize app.
http.listen(app.get('port'), function() {
console.log('App is listening on port', app.get('port'));
});
You did not start your server. In your code, your server is created with this line:
var server = require('http').Server(app);
So, sometime after that, you need to add:
server.listen(80); // or use whatever port number you want the server on
I have resolved this issue by adding following line of code under constructing my express/after var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(3000);
#jfriend00 and #Sablor, Thanks both of you for show me right direction. my server already running on port "3000" so with port 80 its was not working. because it is conflicting with my XAMPP server. Thanks you guys for participating
Trying to set up a basic Express server with a basic pug template.
Can you please tell me what I'm doing wrong here?
'use strict';
//Require Express
var express = require('express');
var app = express();
//Require Pug
var pug = require('pug');
//Require Twitter
var Twitter = require('twitter');
//Set view engine to serve middleware
app.set('view engine', 'pug');
//Set where to look for templates
app.set('views', __dirname + '/templates');
//Set up style sheets
app.use('/static', express.static(__dirname + '/public'));
//Access keys to access twitter account
var config = {
"consumerKey": "",
"consumerSecret": "",
"accessToken": "",
"accessTokenSecret": ""
};
//instantiate twitter client
var client = new Twitter(config);
//Log whether
var error = function (err, response, body) {
console.log('ERROR [%s]', err);
};
var success = function (data) {
console.log('Data [%s]', data);
};
//Set up server on Port 3000
app.listen(3000, function() {
console.log("The frontend server is running on port 3000!");
});
//Render when appropriate
//Tell app to render template
app.get('/'), function(req, res){
res.render('index', {title: 'Hey', message: 'Hello there!'});
}
I'm getting back The frontend server is running on port 3000! in the console.
What am I missing?
I'd really appreciate any help please
You're calling app.get() wrong. You're doing
app.get('/'), function(req, res){
...
Which is two statements separated by the comma operator. The correct syntax is to pass the function as the second argument:
app.get('/', function(req, res){
...
});
I am working on a single page web app using Node + Express and Handlebars for templating. Everything currently works well from index.html, which is served from a pretty standard server.js file:
var express = require('express');
var server = express();
server.use(express.static(__dirname + '/public'));
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
This works perfectly when loading from http://localhost:10001/. My issue is that I'm using push states in the app, so the browser may show a URL like http://localhost:10001/foo/bar and then if I refresh the page, I get the error Cannot GET /foo/bar since there is no route for this.
So my question, and pardon my incredible noobishness when it comes to Node, can I make it so all requests route to index.html? The JavaScript in my app can handle showing the right content based on URL params on page load. I don't want to define custom routes as the number would be large, and the paths for them can change dynamically.
const express = require('express')
const server = express()
/* route requests for static files to appropriate directory */
server.use('/public', express.static(__dirname + '/static-files-dir'))
/* other routes defined before catch-all */
server.get('/some-route', (req, res) => {
res.send('ok')
})
/* final catch-all route to index.html defined last */
server.get('/*', (req, res) => {
res.sendFile(__dirname + '/index.html');
})
const port = 8000;
server.listen(port, function() {
console.log('server listening on port ' + port)
})
This pattern will serve static assets before hitting the catch-all route that serves up your front-end application. To register any additional routes, just add them above the catch-all route.
var express = require('express');
var server = express();
// middleware
server.use(express.static(__dirname + '/public'));
// routes
server.use('*', function (req, res) {
// serve file
});
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
This short thing works well:
import express from "express";
const app = express(),
staticServe = express.static(`${ __dirname }/public`);
app.use("/", staticServe);
app.use("*", staticServe);
Just make sure that all URLs from your HTML/JS files are absolute now, as all resources that do not exist will return index.html file.
Express v 4.15.2
var app = express();
var options = {
dotfiles: 'ignore',
etag: true,
extensions: ['htm', 'html'],
index: 'index.html',
lastModified: true,
maxAge: '1d',
setHeaders: function (res, path, stat) {
res.set('x-timestamp', Date.now());
res.header('Cache-Control', 'public, max-age=1d');
}
};
app.use(compression());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(methodOverride());
app.use('/', express.static(__dirname + '/public', options));
app.use('*', express.static(__dirname + '/public', options));
var express = require('express');
var server = express();
server.use(express.static(__dirname + '/public'));
server.get('*', function(req, res){
res.sendFile('index.html');
});
var port = 10001;
server.listen(port, function() {
console.log('server listening on port ' + port);
});
I have a node.js application and I am stuck getting an error message when I try to load the homepage. I will do my best at laying out my architecture below. It goes index.js --> server.js --> router.js --> requestHandlers.js
I am using a combination of express (www.expressjs.com) and nodebeginner.org. Sorry for the long question.. just wanted to get as much information down as possible.
index.js (creates handle object that contains pathname/requesthandler information, calls function to start server) I start with router.route here and pass it along each step
var server = require("./server");
var router = require('./router');
var requestHandlers = require('./requestHandlers');
// Routes
var handle = {}
handle['/'] = requestHandlers.home;
server.start(router.route, handle)
server.js (starts the server, THIS IS WHERE I WANT TO CONFIGURE THE SERVER, gets a the pathname from the URL, and passes it on to the route module)
var http = require("http");
var url = require('url');
var express = require('express');
function start (route, handle) {
var onRequest = function(request, res) {
var pathname = url.parse(request.url).pathname;
console.log("request for " + pathname + " recieved.");
route(handle, pathname, res);
}
var app = express.createServer(onRequest).listen(8888);
if (app.configure) {
console.log('app exists'); //logging correctly
}
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler());
});
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env); //logs correct with 8888 and development
}
exports.start = start;
router.js (the function route passed from index --> server which calls the route function in router.js, calls the requestHandler that matches the pathname in handle object)
function route (handle, pathname, res) {
console.log("About to route a request for" + pathname); //About to route a request for/stylesheets/style.css SEE BELOW******* this is the error
if (typeof handle[pathname] === 'function') {
handle[pathname] (res);
}
else {
console.log('no request handler found for' + pathname);
}
}
exports.route = route;
requestHandler.js (interacts with the res/req objects, functions are mapped to certain pathnames, only called when those pathnames are requested thanks to the router)
var home = function(res){
res.render('index', { title: 'WWYB?' });
console.log('homepage rendered'); //correctly logs for pathname = '/'
//click();
};
exports.home = home;
***when i go to request localhost:8888 it tries to make a bunch of requests. first it requests "/" correctly but then keeps going through logging everything saying "About to route a request for/stylesheets/style.css" Eventually the page loads with no css. The pathname as indicated in my layout.jade file is exactly that '/stylesheets/style.css'.
Why is the pathname ever evaluating to /stylesheets/style.css? I think node is doing something in the background and I dont fully understand it.
Let me know if you need more info. Thanks!
Like #TJHolowaychuk commented you really should check the manual, and follow a bunch of tutorials. Anyway, I'll try to help you a bit.
The is a very basic explanation. Express allows you to use sub applications, so you can have different part of you application in different files. It has it's own router too. If you need to do something with the request and/or the response before the route is processed, you can create a middleware. If you want you configurations in a different module, then return a function in it.
So an example of server.js :
var $express = require('express'),
app = module.exports = $express.createServer(),
subapp = require('./subapp'),
configure = require('./configure');
// Each of our own configure returns a function that will be
// called by app.configure
app.configure(configure.all(app));
app.configure('development', configure.devel(app));
app.configure('production', configure.prod(app));
// Use our sub application
app.use(subapp);
// Now listen
app.listen(3030)
subapp.js :
var $express = require('express'),
subapp = module.exports = $express.createServer();
// Add a handler for GET / to our sub-application
subapp.get('/', function (req, res) {
res.end('Hello world!');
});
Finally configure.js :
var $express = require('express');
exports.all = function (app) {
return function () {
// Global configurations
app.use($express.bodyParser());
app.use($express.methodOverride());
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use($express.static(__dirname + '/public'));
//...
// If you want to do something with/on the request/response
// you can create a middleware
app.use(function (req, res, next) {
console.log('caught request %s %s', req.method, req.path);
// Don't forget the callback
next();
});
};
};
exports.devel = function (app) {
return function () {
// Development configurations
};
};
//...
Go to localhost:3030 with your favorite browser, it displays "Hello world!", this is our request handler. If you look at the terminal, you'll see "caught request GET /", this is our middleware.
Your stylesheets, client-side javascripts, etc. should be in /public. app.use(express.static(__dirname + '/public')) will serve these.
Let's say you have /public/stylesheets/all.css, then in your jade template you can include it like this link(rel='stylesheet', href='/public/stylesheets/all.css')
Now, you'll have to experiment and learn more about node and express before even thinking to deploy something to production, these websites may help you:
howtonode
nodetuts
Hope this tiny-micro-tut helps you.
woah this is pretty confusing, you might want to start with the app express(1) can generate for you