When i am trying to launch my nodejs server, it does not call the client/public folder. I get the below error, when i point to http://localhost:3000
Error: Not found at
/home/shankar/projects/apiDocs/server/server.js:36:12 at
Layer.handle [as handle_request]
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/layer.js:95:5)
at trim_prefix
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:312:13)
at
/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:280:7
at Function.process_params
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:330:12)
at next
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:271:10)
at
/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:618:15
at next
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:256:14)
at Function.handle
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:176:3)
at router
(/home/shankar/projects/apiDocs/node_modules/express/lib/router/index.js:46:12)
Below is my server.js code
var express = require('express');
var path = require('path');
var logger = require('morgan');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
app.use(express.static(path.join(__dirname, "public")));
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
mongoose.connect('mongodb://127.0.0.1:27017/app', function (error) {
if (error) {
console.log(error);
}
});
app.all('/*', function(req, res, next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Access-Token,X-Key");
if(req.method === 'OPTIONS'){
res.status(200).end();
} else {
next();
}
});
app.all("/api/v1/*", [require('./middlewares/validateRequest')]);
app.use("/", require("./routes"));
app.use(function(req, res, next){
var err = new Error("Not found");
err.status = 404;
next(err);
});
app.set('port', process.env.PORT || 3000);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + server.address().port);
});
I am trying to run my client and my restful services on same server, when i launch my server on port 3000, i expect the client and server to be on the same server.
Folder Structure:
/app
--node-modules
--public
--app //contains all angularjs related files
--assets //contains images and js libraries
--index.html
--server
--server.js
try to use this :
app.use(express.static('./.'));
this is should let express able to see your files
Related
I have a node server and an angularJS app.
I have a route to get informations about one record.
The route is '/pacientes/:id'
When I request data from that route i am getting an error.
What am I doing wrong?
//error:
Error: Can't set headers after they are sent.
at ServerResponse.setHeader (_http_outgoing.js:367:11)
at ServerResponse.header (C:\nodeapp\cloudapp\node_modules\express\lib\respo
nse.js:719:10)
at ServerResponse.send (C:\nodeapp\cloudapp\node_modules\express\lib\respons
e.js:164:12)
at ServerResponse.json (C:\nodeapp\cloudapp\node_modules\express\lib\respons
e.js:250:15)
at C:\nodeapp\cloudapp\server.js:973:10
at Array.forEach (native)
at C:\nodeapp\cloudapp\server.js:971:13
at Layer.handle [as handle_request] (C:\nodeapp\cloudapp\node_modules\expres
s\lib\router\layer.js:95:5)
at next (C:\nodeapp\cloudapp\node_modules\express\lib\router\route.js:131:13
)
at Route.dispatch (C:\nodeapp\cloudapp\node_modules\express\lib\router\route
.js:112:3)
Here is app controller:
angular.module("clinang").controller('ProcedimentosCtrl',['$scope','$http','$state',function($scope,$http,$state){
$scope.modelo={}
var tipoId=$state.params.tipoId;
if (tipoId) {
$http.get('/pacientes/' + tipoId).then(function(response){
$scope.modelo=response.data;
}, function(error){
console.log(error)
});
}
}]);
node - server.js
var express = require('express');
var bodyParser = require('body-parser');
var jwt = require('jsonwebtoken');
var expressJwt = require('express-jwt');
var path = require('path');
var app = express();
// Define the port to run on
app.set('port', process.env.port || 80);
app.use(bodyParser.json());
app.all('*', function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
var pacientes=[
{id:1, nome:'Joao'},
{id:2, nome:'Maria'}
];
app.get('/pacientes/:id', function(req, res) {
pacientes.forEach(function (paciente) {
if (paciente.id == req.params.id) {
res.json(paciente);
return;
}
});
res.status(404).end();
});
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).end();
});
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
You are trying to send multiple responses to the same request from the client, but you can only send it once.
Change this:
pacientes.forEach(function (paciente) {
if (paciente.id == req.params.id) {
res.json(paciente);
return;
}
});
To this:
var result;
pacientes.forEach(function (paciente) {
if (paciente.id == req.params.id) {
result = paciente;
}
});
if (result !== undefined) {
res.json(result);
} else {
res.sendStatus(404);
}
The functions res.json, and res.sendStatus sets the header and the response's body, and call the .end() function after that, so you don't need to do it.
I'm trying to get a polymer web page login to work but seemingly I can't since app.js cannot read the JSON database defined within the file itself. I have uploaded a screenshot of how my folders and files are layered in Visual Studio Code. I'm using a Windows 10 NT OS and Git Bash to run my commands.
THIS IS THE GIT BASH ERROR
Rhino#DESKTOP-NB42TJJ MINGW64
/c/users/rhino/documents/work/personal/polymer-project $ node
demo-server/app.js JSON Server is runnning TypeError: Cannot read
property 'users' of undefined
at C:\users\rhino\documents\work\personal\polymer-project\demo-server\app.js:34:33
at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5)
at next (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5)
at C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:330:12)
at next (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\index.js:271:10)
at C:\users\rhino\documents\work\personal\polymer-project\demo-server\app.js:29:9
at Layer.handle [as handle_request] (C:\users\rhino\documents\work\personal\polymer-project\node_modules\express\lib\router\layer.js:95:5)
THIS IS MY app.js file
var express = require("../node_modules/express");
var app = express();
var path = require("path");
var jsonServer = require("../node_modules/json-server");
var server = jsonServer.create();
var router = jsonServer.router('db.json');
//Authentication Libraries - Start
var cookieParser = require('../node_modules/cookie-parser');
var session = require('../node_modules/express-session');
//Authentication Libraries - End
server.use(cookieParser("security", {"path": "/"}));
app.use(cookieParser("security", {"path": "/"}));
server.use(function(req, res, next) {
res.setHeader("Access
-Control-Allow-Origin", "http://localhost:8080");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS");
res.setHeader("Access-Control-Expose-Headers","Access-Control-Allow-Origin");
res.setHeader("Access-Control-Allow-Headers",
"X-Custom-Header,X-Requested-With,X-Prototype-Version,Content-Type,Cache- Control,Pragma,Origin,content-type");
if (!req.signedCookies.usersession && req._parsedUrl.pathname != "/auth/login" && req.method != "OPTIONS") {
res.redirect('http://localhost:8080/app/pages/auth/auth.html');
}else{
next();
}
});
server.post('/auth/login', function(req, res){
var users = router.db.object.users;
var username = req.query.username;
var password = req.query.password;
for(var i=0;i<=users.length -1;i++){
if(users[i].username == username && users[i].password == password) {
res.cookie('usersession', users[i].id, {maxAge: 9000000, httpOnly: false, signed: true});
res.send(JSON.stringify({success: true}));
return;
}
}
res.send(JSON.stringify({ success: false, error: 'Wrong username or password' }));
});
app.get('/', function(req, res){
if (!req.signedCookies.usersession) {
res.redirect('app/pages/auth/auth.html');
}else{
res.sendFile(path.join(__dirname+'/../app/index.html'));
}
});
app.get('/auth/logout', function(req, res){
res.clearCookie('usersession');
res.redirect('/app/pages/auth/auth.html');
});
/*app.get('/', function(req, res){
res.sendFile(path.join(__dirname+'/../app/index.html'));
});
*/
app.use(express.static(path.join(__dirname, '../')));
var http = require('http').Server(app);
http.listen(8080);
server.use(jsonServer.defaults); //logger, static and cors middlewares
server.use(router); //Mount router on '/'
server.listen(5000, function () {
console.log('JSON Server is runnning')
});
Picture of Visual Studio Code project folder structure
You may need to add middleware as follow in your code:
var jsonServer = require('../node_modules/json-server');
var server = jsonServer.create();
var router = jsonServer.router('db.json');
var middlewares = jsonServer.defaults(); //<--- new line
then in your server.use(jsonServer.defaults); //logger, static and cors middlewares, inject middleware as shown:
server.use(middlewares); //logger, static and cors middleware
I am working through Pluralsight's RESTful Web Services... tutorial, but am running into an error very early on.
The error is:
...\node_modules\mongoose\node_modules\mongodb\lib\server.js:228
Error: connect ECONNREFUSED
at exports._errnoException (util.js:746:11)
at ICPConnectWrap.afterConnect [as oncomplete] (net.js:1010:19)
This is the app.js file:
var express = require('express'),
mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost/bookAPI');
var Book = require('./models/bookModel');
var app = express();
var port = process.env.PORT || 8080;
var bookRouter = express.Router();
bookRouter.route('/Books')
.get(function(req, res){
Book.find(function(err, books){
if(err){
console.log(err);
}
else{
res.json(books);
}
});
});
app.use('/api', bookRouter);
app.get('/', function(req, res){
res.send("Here");
});
app.listen(port, function(){
console.log("Gulp is running my app on PORT: " + port);
});
It runs fine if I comment out
var db = mongoose.connect('mongodb://localhost/bookAPI');
I'm making a single page app with Angular routes on the front end, but the backend is giving me grief.
All the routes that involve interfacing with the database work, but when I add in a route (Copying the exact same structure) to send an html file, or just hello world, it returns a 404, not even registering on the node console (with one weird exceptions noted below).
I read this post explaining how static should come after routes, it makes sense, but it's not working on my code.
app.js is as follows:
// SETUP
var express = require('express');
var app = express();
var router = express.Router();
var mongoose = require('mongoose');
var port = process.env.PORT || 3001;
var database = 'mongodb://example-database...';
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
// CONFIG
mongoose.connect(database);
// Note: response parser must be placed before routing
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.set('jsonp callback name', 'cb');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(router);
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
next();
});
// ROUTES
require("./routes/api_chirp.js")(router);
require("./routes/api_video.js")(router);
require("./routes/api_interaction.js")(router);
require("./routes/api_user.js")(router);
require("./routes/api_search.js")(router);
require("./routes/api_jsonp.js")(router);
require("./routes/index.js")(router);
app.use(express.static(path.join(__dirname, 'public')));
// ERROR HANDLING
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
module.exports = app;
app.listen(port);
console.log("App listening on port " + port);
index.js (Note: The same structure used in other working API routes (using an alternative route, i.e. "/api/someroute")
module.exports = function(router) {
router.route('/workspace') // Only works if route is prefixed with "api_someword", "someword" itself won't work.
.get(function(req, res) {
console.log('request received');
res.send('hello world');
}); // Ends - Post
};
Question: I'm at the end of my rope... ANY suggestions, answers will help at this point. How do I get that route in index.js working?
// ROUTES
require("./routes/api_chirp.js")(router);
require("./routes/api_video.js")(router);
require("./routes/api_interaction.js")(router);
require("./routes/api_user.js")(router);
require("./routes/api_search.js")(router);
require("./routes/api_jsonp.js")(router);
require("./routes/index.js")(router);
pass the app object like this
// ROUTES
require("./routes/api_chirp.js")(app);
require("./routes/api_video.js")(app);
require("./routes/api_interaction.js")(app);
require("./routes/api_user.js")(app);
require("./routes/api_search.js")(app);
require("./routes/api_jsonp.js")(app);
require("./routes/index.js")(app);
Solved:
Another developer putting a path filter on nginx that prevented any url that didn't have isn't prefixed with /api to get through to node. I added it and it solved the problem.
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!