node js GET 404 (Not Found) - javascript

I am new to node.js. i am running nodejs from bin/wwww and getting "jquery.min.js:4 GET http://127.0.0.1:3000/file.js 404 (Not Found)" error. I am trying very basic and simple thing in a simple web page. Just trying to execute a file on server through ajax call but it always shows file not found error.
In my html page (firstpage.html) i am trying which i want as client request.
<!DOCTYPE html>
<html>
<head>
<meta content="en-us" http-equiv="Content-Language">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<link rel="stylesheet" type="text/css" href="stylesheets/myButton.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
var dataString;
$(document).ready(function(){
$.ajax({
type: "GET",
url: 'file.js',
data: dataString,
success: function(data){
console.log(data);
}
});
});
</script>
</head>
<body>
<p class="auto-style1"><strong>Welcome to MyPage</strong></p>
<div >
<input class="myButton" type="button" onclick="readTextFile(test.txt)" value="Submit" />
</div>
<button id="bb">QUERY</button>
</body>
</html>
and i have a file (file.js) at server ,
var fs = require("fs");
console.log("Going to write into existing file");
fs.writeFile('input.txt', 'Simply Easy Learning!', function(err) {
if (err) {
return console.error(err);
}
console.log("Data written successfully!");
console.log("Let's read newly written data");
fs.readFile('input.txt', function (err, data) {
if (err) {
return console.error(err);
}
console.log("Asynchronous read: " + data.toString());
});
});
Currently file.js and index.txt are in myapp\public\javascripts location. my app.js is as below,
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var firstpage = require('./routes/firstpage');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
Am i making some mistake in configuration ? please help.

Your express is never told what to serve when file.js is requested.
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Because it's not ., /users, or /firstpage it defaults to the 404 error and returns that. And because it's a js file, you need to use express's static middleware function.
app.use(express.static('routes');
Should be what you want, I would place it after
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
Such that:
app.use('/', index);
app.use('/users', users);
app.use('/firstpage', firstpage);
app.use(express.static('routes');
Beware, this will allow anything in the routes folder to be accessed statically, so you're going to either want to move all your static resources somewhere else, or block off anything in the routes folder you don't want accessed this way.

Your ajax request point to the public folder but the file leaves in the javascripts subdirectory... Try moving the file you request in the public folder or change the request URL to point the correct folder structure...

Check this out: https://github.com/mdn/express-locallibrary-tutorial
https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs
// Catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// Error handler
app.use(function(err, req, res, next) {
// Set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// Render the error page
res.status(err.status || 500);
res.render('error');
});

Related

Linking HTML form action to node js function

I'm trying to execute a function in node.js when a users enters information on a form in html. I keep getting 404 not found and am not sure where to go. I'm sure there are other questions similar to this but have searched around and can't find anything.
HTML Code:
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Home</title>
</head>
<link rel = "stylesheet"
type = "text/css"
href = "style.css" />
<form action="/zipCheck" method="post" accept-charset="utf-8">
<input placeholder="Enter your zip code to start" class = "zipInput">
</form>
</html>
Node.js code:
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
console.log("hello");
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(logger('short'));
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.post('/zipCheck', function(req, res){
console.log("GOOD");
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
The order of middleware loading is important: middleware functions that are loaded first are also executed first.
You added the /zipCheck route after the error handler, your requests will never reach this handler and
your app will not print GOOD.
You need to reorder your routes handler, also add a slash before zipCheck
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.post('/zipCheck', function(req, res){
console.log("GOOD");
});
// error handler
app.use(function(err, req, res, next) {
})

Why router in Express/node.js return 404

I just generated Express app and added custom route (/configuration). But if I try to open http://localhost:3000/configuration, server returns 404 Not Found error. I checked the code and don't understand where is error.
app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var config_page = require('./routes/configuration');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/configuration', config_page);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
routes/configuration.js (routes/index.js is similar)
var express = require('express');
var router = express.Router();
/* GET configuration page. */
router.get('/configuration', function(req, res, next) {
res.render('configuration', { title: 'My App | Configuration' });
});
module.exports = router;
This code is the problem
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
Also the current Url which is generated by your application is http://localhost:3000/configuration/configuration. If you make a query on this then it will work. Now if you wan to use it with http://localhost:3000/configuration. then you need to remove on path from anywhere. May be you can change in main file like this
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/',config_page); //-----------> this is the line you need to change
How can it be used for error handling. Remove it and add this code to catch any error in application.
process.on('uncaughtException', function (err) {
// This should not happen
logger.error("Pheew ....! Something unexpected happened. This should be handled more gracefully. I am sorry. The culprit is: ", err);
});

Node.js Express POST 404

I am new to Node.js (been doing ASP.Net for ages) and I cannot for the life of me figure out why I am getting this 404.
So in my work on this I have simplified the code down to just the bare minimum.
app.js for the service handler.
app.post('/getdocument', function (req, res) {
console.log('made it');
res.send('made it');
});
The code from the jade file
li: a(onclick="downloadfile('#{pdfUrl}');") Download PDF
And the onclick function
function downloadfile(url){
alert(url);
$.post('/getdocument', {data: url}, function (data) {
alert(data);
});
}
So I get the first alert that it made it into the function, then I get this in the log for the Node Server
POST /getdocument 404 81.910 ms - 1547
I am really at a loss as to why.
-- As Requested here is the entire app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var viewer = require('./routes/viewer');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use('/pdf', express.static(path.join(__dirname, 'public/pdf')));
app.use('/ViewerJS',express.static(path.join(__dirname, 'ViewerJS')));
app.use('/viewer', viewer);
app.post('/getdocument', function (req, res) {
console.log('made it');
res.send('made it');
});
// catch 404 and forward 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.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
So it all turned out to be an issue with Node server running. I had to restart to apply Windows updates and now it works.
Take care all!

Getting response after posting to mongodb

I tried testing my code written to post data to mongodb via postman using x-www-formurlencoded but I keep getting this error:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" href="/stylesheets/style.css">
</head>
<body>
<h1>Not Found</h1>
<h2>404</h2>
<pre>Error: Not Found
at Layer.app.use.res.render.message [as handle] (c:\Users\Tomix\Documents\Source\Tomix\app.js:39:15)
at trim_prefix (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:226:17)
at c (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:198:9)
at Function.proto.process_params (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:251:12)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:189:19)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:166:38)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:150:14)
at next (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:166:38)
at Function.proto.handle (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:234:5)
at Layer.router (c:\Users\Tomix\Documents\Source\Tomix\node_modules\express\lib\router\index.js:23:12)</pre>
</body>
<!--Live reload script -->
<script type="text/javascript" src="http://localhost:35729/livereload.js"></script>
</html>
So what am trying to do is to create an e-commerce website with mean stack,so am trying to structure the app files and folder to reflect the server side and the client side.
The code here is to save data to database (mongodb), but from the error message I was able to deduce is that at the point it ought to return response in json format it throws the error message.
exports.create = function(req, res) {
console.log('I got called', req.body);
var product = new Product(req.body);
product.save(function(err) {
if (err) {
return res.send(400, {
message: err
});
} else {
res.json(product);
}
});
};
My app.js file
'use strict';
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var routes = require('./routes/index');
var users = require('./routes/users');
/*connecting the to database*/
require('./config/db');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'app/views'));
app.set('view engine', 'jade');
app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride('X-HTTP-Method-Override'));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
/// 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.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
next();
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
next();
});
//Routes
require('./app/routes/product.server.routes.js')(app);
exports = module.exports = app;
Please am stuck have search online for possible solution, some of the suggestion I got was I need to add method-override to my express configuration.
I think that you missed a part of the equation:
Post/Info -> Connector/Driver -> Mongodb/Database
Yo can not post JSON to mongo via Postma. You'll need to find a mongodb solution for javascript to play with it. You can try it with Node.js for example. Here I give you a list of all the language possibilities to connect to mongo.
http://docs.mongodb.org/ecosystem/drivers/
Hope it helps!

Failed to lookup view "error" in views directory using handlebars

I am new with express and handlebars. I wanted to use handlebars as a template engine on my express.js app but then I keep on receiving this kind of error:
which was get generated by this code
var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbr = require('express3-handlebars'); // "express3-handlebars"
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views/'));
//app.set('view engine', 'jade');
app.engine('handlebars', exphbr({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
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('/', routes);
app.use('/users', users);
/// catch 404 and forward 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.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
what else am I missing or am I doing it right? Please help, I have been stuck for 1 day.
The issue is the following line
app.set('views', path.join(__dirname, 'views/'));
Express is looking for a file called error.jade in the folder views. If the file exists, possibly try removing the extra / from views/.
I just ran into a similar problem because I moved the views folder into another folder called app_server so the solution was to replace the line with
app.set('views', path.join(__dirname, '/app_server/views'));
You should have a View within your application currently named error.jade. Because you set up your application to use Handlebars the view engine is attempting to look for error.handlebars.
You should put modify the file and that will do it.
I had this issue when I upgraded the server.
All I had to do is run this
npm update
If the view engine is not set to jade/pug you have to use the extension right here:
app.use(function(err, req, res, next) {
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error.pug'); <<<<<HERE!
});

Categories