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!
Related
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');
});
The basic problem is as follows:
Passing an object from my c# program, which is serialize and send through a socket. Achieved this in node.js/express application with socket.io.
Need to pass this to the client and using pug as the template engine.
Everything tried so far just doesn't seem to be working. Can't access the elements in the object. Pretty new to node and express so please bear with me.
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 routes = require('./app_server/routes/index');
var users = require('./app_server/routes/users');
var app = express();
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
// view engine setup
app.set('views', path.join(__dirname, 'app_server', 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', routes);
app.use('/users', users);
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
// 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;
layout.jade :
doctype html
html
head
meta(name='viewport', content='width=device-width, initial-scale=1.0')
title= title
link(rel='stylesheet', href='/bootstrap/css/amelia.bootstrap.css')
link(rel='stylesheet', href='/stylesheets/style.css')
script(src="https://cdn.socket.io/socket.io-1.4.5.js")
script.
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
body
block content
script(src='/javascripts/jquery-1.11.1.min.js')
script(src='/bootstrap/js/bootstrap.min.js')
index.jade :
extends layout
block content
h1= title
p Welcome to #{title}
//THIS IS WHERE I DON'T KNOW HOW TO ACCESS THE OBJECT AND ITS PROPERTIES
Can see the object in the console so the data is appearing.
Tried many different variations, but nothing seems to be working. Any input or guidance would be welcome.
Thanks in advance.
I am creating an upload/download app, i don't know why its only my app.js file is having this problem. I searched all other answers on the internet but still it did not solve the problem.
here is the code below:
var express = require('express');
var path = require('path'); // add path to set and get
var fs = require('fs'); // add filesystem
var connect = require('connect');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var connect = require('connect');
var http = require('http');
var routes = require('./routes/index');
var users = require('./routes/users');
//var upload = require('./routes/upload');
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(express.static('public'));
app.use(express.static('files'));
app.use('/', routes);
app.use('/users', users);
//app.use('/upload',upload);
// 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;
Thanks for your help.
check in your all files
make sure you don't miss export it
module.exports = router;
Router.use() at all times requires a Middleware function as an argument. Assuming your route to download some files from your server, it should Look similar to this.
var Router = express.Router();
function downloadFiles(request,response) {
// some code to dowload files
}
// The above function which takes request and response
// should be passed to Router.use()
Router.use(downloadFiles);
When you that error it means that what you passed to Router.use() is not a middleware function like downloadFiles.
I created an express project using the express generator like following
express project_name
and
npm install
This is my 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 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');
// uncomment after placing your favicon in /public
//app.use(favicon(__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('/', 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;
These are my routes
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'iDanG Management' });
});
module.exports = router;
I have following index.jade
extends layout
block content
div.container
div.row
form(id='myform' action='' method='post')
p Name:
input(type='text' name='name')
p E-Mail:
input(type='text' name='email')
input(type='submit' value='add')
table(class='table table-hover' id='user_table')
thead
tr
th Name
th Email
tbody
script.
$(document).ready(
function() {
$('#user_table').dataTable({
"pagingType": "simple_numbers",
"ordering": false
});
$('#myform').ajaxForm({ beforeSubmit:
function (formData, jqForm, options) {
$('#table').DataTable().row.add([formData[0].value, formData[1].value]).draw();
return false;
}
});
});
And following layout.jade
doctype html
html
head
title= title
script(src="/javascripts/jquery-1.11.2.min.js")
script(src="/javascripts/jquery.form.js")
script(src="/javascripts/jquery.dataTables.min.js")
link(rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css")
link(rel="stylesheet" href="/javascripts/jquery.dataTables.min.css")
body
block content
when I try to submit that form I receive following error:
Error: Not Found
at app.use.res.render.message (/home/ubuntu/iDanG_Management/app.js:30:13)
at Layer.handle [as handle_request] (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/layer.js:82:5)
at trim_prefix (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:302:13)
at /home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:270:7
at Function.proto.process_params (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:321:12)
at next (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:261:10)
at /home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:603:15
at next (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:246:14)
at Function.proto.handle (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:166:3)
at router (/home/ubuntu/iDanG_Management/node_modules/express/lib/router/index.js:35:12)
For the forms I used this
Do you have any suggestions how I can solve this problem? Help is highly appreciated!
It seems like you are doing a post request and your routes does not have post handler.
May be add route for post:
router.post('/', function(req, res, next) {
//do something and return data here?
});
Noob - trying to set up CRUD using routes on Express4 and Node. I've got the following GET and POST routes working ok, but DELETE and PUT are giving 404, Not Found errors, which is strange.
I'm using Postman for Chrome and have set the Content Type to application/json, and this is working ok - i do notice that on the DELETE and PUT queries the header still notes that it's sending as text/html, rather than JSON, although I've set both the RAW settings to JSON, and the Headers content type manually to application/json.
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var Todo = require('../models/Todo.js');
/* GET /todos listing. THIS IS WORKING*/
router.get('/', function(req, res, next) {
Todo.find(function (err, todos) {
if (err) return next(err);
res.json(todos);
});
});
/* POST /todos listings THIS IS WORKING*/
router.post('/', function(req, res, next){
Todo.create(req.body, function(err, post){
if (err) return next(err);
res.json(post);
});
});
/* GET /todos/id THIS IS WORKING*/
router.get('/:id', function(req, res, next) {
Todo.findById(req.params.id, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
/* DELETE /todos/:id NOT WORKING*/
router.delete('/:id', function(req, res, next) {
console.log(req);
Todo.findByIdAndRemove(req.params.id, req.body, function (err, post) {
if (err) return next(err);
res.json(post);
});
});
module.exports = router;
Also this is a routes.js script that is being imported into app.js (see 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 routes = require('./routes/index');
var todos = require('./routes/todos');
// set our port
var port = process.env.PORT || 3000;
//Requires the mongoose connection
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp', function(err) {
if(err) {
console.log('connection error', err);
} else {
console.log('connection successful');
}
});
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(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/todos', todos);
// 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: {}
});
});
// start app ===============================================
// startup our app at http://localhost:3080
app.listen(port);
// shoutout to the user
console.log('Magic happens on port ' + port);
module.exports = app;
I looked into your implementation, it looks fine. Just one chance where i feel it can go wrong is, if we look into the documentation of Model.findOneAndRemove(conditions, [options], [callback]), you are going wrong in [options].
In [options] we can do :
sort: if multiple docs are found by the conditions, sets the sort
order to choose which doc to update
select: sets the document fields to return
Try this, i hope it will solve your problem.
You mentioned that, PUT is also having same 404 issue, could you please update your post by including same. Let's understand where it is going wrong.
There's a couple of things you might want to check.
Your POST is working as intended, but your DELETEs and your PUTs aren't. You've set the content type to application/json.
Given that you are using Express 4, and had to include a body parser yourself, do you happen to include the following lines?
var app = express();
// you probably have this, for application/x-www-form-urlencoded
app.use(bodyParser.urlencoded());
// extrapolating here, you only mentioned you were receiving 404s.
// you might be missing the following line?
app.use(bodyParser.json());
In your delete route, you log the response object, is this a typo? A more useful log would be of the request object - so you can determine what exactly the route thinks you sent.
Shot in the dark, but in the absence of additional information, I hope at least one of the answers are correct.