I'm getting this error "NetworkError: 404 Not Found - http://localhost:3000/socket.io/socket.io.js" and I don't know how can I fix it. I have tried changing the port, adding the link with the port ... and I have no idea.
My app.js :
var express = require('express')
, http = require('http')
, stylus = require('stylus')
, nib = require('nib')
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
function compile(str, path) {
return stylus(str)
.set('filename', path)
.use(nib());
}
app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.logger('dev'))
app.use(stylus.middleware(
{ src: __dirname + '/public'
, compile: compile
}
))
app.use(express.static(__dirname + '/public'))
app.get('/', function (req, res) {
res.render('index',
{ title : 'Home' }
)
})
app.listen(3000)
note: The console said it's ok ( info - socket.io started )
Anyway I have tried this
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
but doesn't print the port, say me undefined
You are creating an express HTTP server as well as a standard HTTP server. The app in your example above refers to the Express app which does not have .get('port'); method, try using server.listen. For example:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.get('/', function(req, res) {
res.send("Hello World!");
});
server.listen(3000);
console.log('Express server started on port %s', server.address().port);
Related
I would like to set new.html as the base file for the server, but it keeps defaulting to index.html
My code is below...
const express = require('express');
const app = express();
// Set '/public' as the static folder.
app.use(express.static(__dirname + '/public'));
// Set index.html as the base file
app.get("/", function(req, res) {
res.sendFile(__dirname + '/new.html');
});
var server = app.listen(4000, function() {
console.log('Listening to requests on port 4000');
});
You can specify the index file to use as an option to express.static():
const express = require('express');
const app = express();
// Set '/public' as the static folder.
app.use(express.static(__dirname + '/public', {
index: 'new.html'
}));
const server = app.listen(4000, function() {
console.log('Listening to requests on port 4000');
});
Then, you no longer need the / route.
Alternatively, you could specify your / route before your static directory:
const express = require('express');
const app = express();
// Set new.html as the base file
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/new.html');
});
// Set '/public' as the static folder.
app.use(express.static(__dirname + '/public'));
const server = app.listen(4000, function() {
console.log('Listening to requests on port 4000');
});
Note: the file path should be /public/new.html rather than /new.html.
I have the following code which is defaulting to use HTTPS, I'm just unclear how to send an index.html file back
var express = require('express'),
path = require('path'),
fs = require('fs'),
app = express(),
staticRoot = __dirname + '/',
httpsRedirect = require('express-https-redirect');
app.set('port', (process.env.PORT || 3001));
app.use('/', httpsRedirect())
app.listen(app.get('port'), function () {
console.log('app running on port', app.get('port'));
});
Any help is greatly appreciated
You can send the html file usually asfollows
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname + '/index.html'));
});
Note: express-https-redirect middleware redirects non-secure access to HTTPS Only.
I'm having a problem routing in express 4. I was following the example, but it isn't loading. I'm just getting a spinning wheel.
How do you do routing in express version 4?
app.js:
var express = require('express');
var http = require('http');
var app = express();
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
var port = (process.env.PORT || process.env.VCAP_APP_PORT || 5000);
app.use('/birds', require('./controller/bird'));
http.createServer(function (req, res) {
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end('Hello World!\n');
}).listen(port);
console.log('Server running at http://127.0.0.1:'+port);
bird.js:
var express = require('express');
var router = express.Router();
// middleware specific to this router
router.use(function timeLog(req, res, next) {
console.log('Time: ', Date.now());
next();
});
// define the home page route
router.get('/', function(req, res) {
res.send('Birds home page');
});
// define the about route
router.get('/about', function(req, res) {
res.send('About birds');
});
module.exports = router;
You're not calling the app.listen() function. Instead of the http.createServer one, you should invoke the Express function.
Please, take a look at a basic example.
Relevant code:
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
});
Edit: as slebetman wrote in the comment, the more general way for it is:
http.createServer(app).listen(port, function(){
console.log('now listening on port ' + port);
});
I got a very similar problem with this post Learning Node - Express Public folder not working
I added to my server.js
app.use("public",express.static(__dirname + '/public'));
But when I do
http://localhost:8081/public/css/styles.css
http://localhost:8081/styles.css
Neither works. I got "Cannot GET /public/css/styles.css" and "Cannot GET /styles.css" respectively.
Here is my server.js
var express = require('express')
, cors = require('cors')
, app = express()
, mongoose = require('mongoose')
, models = require('./models')
, bodyParser = require('body-parser')
, controllers = require('./controllers')
, port = 8081//process.env.PORT || 3000
// Config
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());
app.set('views', __dirname + '/views')
app.set('view engine', 'ejs');
app.engine('html', require('ejs').renderFile);
app.use("public",express.static(__dirname + '/public'));
app.use('/', controllers);
mongoose.set('debug', true);
mongoose.connect('mongodb://localhost/db', function (err) {
if (err) throw err;
console.log("mongoose connected")
var server = app.listen(port, function () {
var host = server.address().address
var port = server.address().port
console.log("RESTful Web Services listening at http://%s:%s", host, port)
})
})
Here is the index.js in the controller folder
var express = require('express')
, router = express.Router()
, users = require('./api/users.js')
router.use('/api/user', users);
router.get('/', function (req, res) {
res.render('index.html')
})
//router.use(express.static('public'));
//router.use(express.static('views'));
router.get('/views/demo', function (req, res) {
res.sendFile('/views/demo.html')
})
module.exports = router
Actually, if I run
http://localhost:8081/views/demo.hmtl
I would again get "Failed to load resource: the server responded with a status of 404 (Not Found)"
What did I miss?
I added the following to the server.js and it worked.
app.use('/views', express.static(path.resolve(__dirname, 'views')));
app.use('/public', express.static(path.resolve(__dirname, 'public')));
I am trying to print the post data on my console
app.js
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 7002);
app.use(express.static(__dirname + '/public/images'));
app.post('/Details/',function(request,response,next){
app.use(express.bodyParser());
var keyName=request.query.Key;
console.log(keyName);
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Initial snapshot::
I test with POST-MAN with below data::
Now i get error as::
I just want to print the data i recieved from postman that is dev
..... which is being displayed as undefined ?
How to resolve this !
[Edit] ---- Adding body parser outside the route
var express = require('express')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 7002);
app.use(express.static(__dirname + '/public/images'));
app.use(express.bodyParser());
app.post('/Details/',function(request,response,next){
var keyName=request.query.Key;
console.log(keyName);
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Still have same error
Instead of query:
var keyName=request.query.Key;
console.log(keyName);
use body:
var keyName1=request.body.key;
console.log(keyName1);
Code:
var express = require('express')
, async = require('async')
, http = require('http');
var app = express();
app.set('port', process.env.PORT || 7002);
app.use(express.static(__dirname + '/public/images'));
app.use(express.bodyParser());
app.post('/Details/',function(request,response,next){
var keyName1=request.body.key;
console.log(keyName1);
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/post/', function(req, res) {
// print to console
console.log(req.body);
// just call res.end(), or show as string on web
res.send(JSON.stringify(req.body, null, 4));
});
app.listen(7002);
Use request.query when you have querystring params.
For form/post data use req.body.
In your case, use request.body.key.
An update on using the middleware, body-parser, for later versions of Express: Using app.use(express.bodyParser()) will report an error such as:
Error: Most middleware (like bodyParser) is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.
This can be addressed by first installing the body-parser middleware:
npm install body-parser
then write code such as:
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
and then accessing the body of the request object, for example, console.log(req.body)
You can't call app.use(express.bodyParser()); inside middleware/route handler:
request should pass through bodyParser() before it reaches route handler
you will be adding new bodyParser()s in each request, but they will be after app.router and will never work
Use built in function "util" to print any type of json data in express js
var util = require("util");
console.log(util.inspect(myObject, {showHidden: false, depth: null}));