I'm currently writing a web application with the MEAN stack, and am testing to see if my nodejs server is working. Here's my server.js:
// server.js
'use strict';
// modules =================================================
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
// expose app
exports = module.exports = app;
I currently have it redirecting all routes to my index.html file to test to make sure my views are working. Here's my routes.js:
// models/routes.js
// grab the user model
var User = require('./models/user.js');
module.exports = {
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
However, when I try to run node server.js, it gives me this error:
/home/hess/Projects/FitTrak/app/routes.js
app.get('*', function(req, res) {
^
SyntaxError: Unexpected token .
Does anyone have any idea what's causing this? I checked and all my braces and parentheses are all closed and written correctly.
As Jose Hermosilla Rodrigo said in his comment, you're declaring the object literal module.exports wrong. It should look like this instead:
module.exports = function(app) {
app.get('*', function(req, res) {
res.sendfile('./public/index.html'); // load our public/index.html file
});
};
just try this code...
// models/routes.js
var express=require('express');
var app=express();
// TODO: Add all routes needed by application
// frontend routes =========================================================
// route to handle all angular requests
app.get('*', function(req, res) {
res.sendfile('./public/index.html');
});
module.exports = route;
server.js
'use strict';
const path = require('path');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
var route=require('./models/route.js');
const methodOverride = require('method-override');
// configuration ===========================================
// config files
const db = require('./config/db');
// set our port
var port = process.env.PORT || 8080;
// connect to mongoDB
// (uncomment after entering in credentials in config file)
// mongoose.connect(db.url);
// get all data/stuff of the body (POST) parameters
// parse application/json
app.use(bodyParser.json());
// parse application/vnd.api+json as json
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));
// override with the X-HTTP-Method-Override header in the request simulate DELETE/PUT
app.use(methodOverride('X-HTTP-Method-Override'));
// set the static files location /public/img will be /img for users
app.use(express.static(__dirname + '/public'));
// routes ==================================================
require('./app/routes')(app); // configure our routes
// start app ===============================================
// startup our app at http://localhost:8080
app.listen(port);
// shoutout to the user
console.log('App running on port ' + port);
app.use('/',route);
If you are using MEAN stack I would suggest you to use express own router middleware to handle all your routes. Just include.
var router = express.Router();
//use router to handle all your request
router.get(/xxx,function(req, res){
res.send(/xxxx);
})
// You may have n number of router for all your request
//And at last all you have to do is export router
module.exports = router;
Related
so I'm trying to make a simple "route system", that would handle requests and send them to a certain controller.
The problem is that I can't even handle any route, because I get
Cannot GET /
error in response.
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
const express = require('express')
const app = express()
// Route config
const routes = {
['/']: {
controller: 'index',
method: 'get'
},
}
// Load routes
const load = () => {
for (const route in routes) {
app[routes[route].method](route, (req, res) => {
// Do something
})
}
}
exports.load = load
You don't use your router file in app.js, try that:
app.js
const express = require('express')
const router = require('./routes/routes')
const app = express()
const port = 3000
app.engine('.html', require('ejs').__express)
app.set('view engine', 'html')
app.use('/', router);
router.load()
app.listen(port, () => {
console.log(`Waiting on :${port}`)
})
routes.js
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) { res.send({ success: true }); });
module.exports = router;
It's useless and unreadeable create an array whit your all your routes.
My suggestion is to try use command by terminal express my_app for generate the base structure and try to use it or at least read for see how it's work.
You seem to be lacking the context for how the routing system works within Express.
As a starting point, please create a project with the below structure, and try creating your own route to ensure you have a grasp on how to utilize them properly.
Create a new project folder
cd into the project folder from within your terminal
run npm init -y
Run npm i express dotenv
Create a file named app.js in the root of your project folder and place the below code inside of it:
require('dotenv').config();
const express = require('express');
const app = express();
app.use(express.json({limit: '30mb', extended: true}));
app.use(express.urlencoded({ extended: true }));
app.listen(process.env.PORT || 3000, () => {console.log('Server successfully started')});
app.get('/', (req, res) => {
return res.send('Hello, World!');
});
Create a new folder named routes
Create a new file named test.js and place it inside of the routes folder
Place the below code in the test.js file.
const router = require('express').Router();
router.get('/', (req, res) => {
return res.send('Hello from your custom route!');
});
module.exports = router;
Go back into your app.js file and add the below lines of code to the bottom of the file
const testRoute = require('./routes/test');
app.use('/test', testRoute);
In your terminal, run node app.js
Make a GET request to http://localhost:3000/test by navigating to it with your browser, or by using a REST client, such as Postman.
Once you have completed these steps, you should understand the basic concept of Express routing.
You can use the router combined with Express Middleware to re-route your user to the proper controller based on the endpoint they are trying to access / the data they are trying to send.
Please test with this code
const express = require('express')
const app = express();
app.get('/', (req, res) => {
res.json({"message": "Welcome! it's working"});
});
The complete code is here on Github
trying to get my data after creating it in mongodb from localhost:3000/todos/ and i get the error in node [UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client] i make use of the following
// Require Express
const express = require("express");
// Setting Express Routes
const router = express.Router();
// Set Up Models
const Todo = require("../models/todo");
// Get All Todos
router.get("/", async (req, res) => {
try {
const todo = await Todo.find();
res.json(todo);
} catch (err) {
res.json({ message: err });
}
});
this is my app.js with the necessary route to localhost:3000/todos/
// Require Express
const express = require("express");
const app = express();
// Require Body-Parser
const bodyParser = require("body-parser");
// Require Cors
const cors = require("cors");
// Middlewares - [Set bodyParser before calling routes]
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// Import Routes
const todoRoutes = require("./routes/todo");
// Setup Routes Middlewares
app.use("/", todoRoutes);
app.use("/todos", todoRoutes);
i want to see to see my output daata on localhost:3000/todos/ but i get it on localhost:3000/ . Thanks
ok i got a hang of it and it was my routes causing it i just adjusted where the route was to be directed.
// Import Routes
const todoRoutes = require("./routes/todo");
// Setup Routes Middlewares
app.use("/todos", todoRoutes);
I am writing a simple MEAN app, and I am currently working on the routes.
In my server.js, I have
var express = require('express');
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
var sizeOf = require('image-size');
var app = express();
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
// configuration ===========================================
require('./app/models/Purchase');
require('./app/models/Seller');
require('./app/models/User');
// config files
var db = require('./config/db');
var port = process.env.PORT || 8080; // set our port
// mongoose.connect(db.url); // connect to our mongoDB database
// get all data/stuff of the body (POST) parameters
app.use(bodyParser.json()); // parse application/json
app.use(bodyParser.json({ type: 'application/vnd.api+json' })); // parse application/vnd.api+json as json
app.use(bodyParser.urlencoded({ extended: true })); // parse application/x-www-form-urlencoded
app.use(methodOverride('X-HTTP-Method-Override')); // override with the X-HTTP-Method-Override header in the request. simulate DELETE/PUT
app.use(express.static(__dirname + '/public')); // set the static files location /public/img will be /img for users
// routes ==================================================
var routes = require('./app/routes/routes');//(app); // pass our application into our routes
var price = require('./app/routes/pricing');
var processing = require('./app/routes/processing');
var uploads = require('./app/routes/uploads');
var seller = require('./app/routes/seller');
app.use('/', routes);
app.use('/price', price);
app.use('/processing', processing);
app.use('/uploads', uploads);
app.use('/seller', seller);
// start app ===============================================
app.listen(port);
console.log('Magic happens on port ' + port);
exports = module.exports = app;
Then, in my route, I have
var express = require('express');
var mongoose = require('mongoose');
var Seller = mongoose.model('Seller');
var router = express.Router();
router.get('/', function(req,res){
res.json({message: 'youre in router.get'});
});
router.post('/registerSeller', function(req,res,next){
console.log('You made it all the way to seller route!');
res.json({message: "you did it"});
next();
});
module.exports = router;
When I start my node server, everything goes well. When I use Postman to POST to the above route, it just 'hangs' and eventually gives an error message that it cannot connect. In Postman, I select 'POST' to http://localhost:8080/seller/registerSeller.Clicking 'code', I get
POST /seller/registerSeller HTTP/1.1
Host: localhost:8080
Cache-Control: no-cache
Postman-Token: 070cb9b3-992a-ffd6-cede-c5b609bc9ce5
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Looking at the browser's developer tools, it shows a POST being made, and then after a while, it also reads that the POST failed.
Could anyone tell me what I'm doing wrong? Thank you.
The problem is that you are responding and then trying to call the next() function in the router stack.
router.post('/registerSeller', function(req,res,next){
console.log('You made it all the way to seller route!');
return res.send({message: "you did it"});
//next(); remove this shit.
});
This should work. Express middlewares go in order. So if you need to have a middleware to be called before this function, then you have to put it before in the stack. If you need to do something after this function, forget about the res.json... part.
I'm trying to follow this tutorial, in which the author provides a sample code:
// server.js
// BASE SETUP
// =============================================================================
// call the packages we need
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
res.json({ message: 'hooray! welcome to our api!' });
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Magic happens on port ' + port);
And I tweaked it a little bit and here is my code:
'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8081;
var router = express.Router();
router.get('/', function(req, res, next) {
res.json({ message: 'Hello World!' });
});
app.use('/api', router);
app.listen(port);
console.log('Magic happens on port ' + port);
The server runs perfectly but when I visit localhost:8081, I get the following message on my browser: Cannot GET /
What am I doing wrong here?
Since you added app.use('/api', router);
And your route is router.get('/', function(req, res, next) { res.json({ message: 'Hello World!' }); });
Then to access '/' you need to request with /api/
Update: If you have set the port on in env use that port or else you should be able to access using localhost:8081/api/
Hope it helps !
The above comment is correct.
You have added prefix '/api' to your local server and all incoming request will be http://localhost:<port>/api/<path>
app.use('/api', router);
If you want to access like this (without prefix) http://localhost:<port>/<path>
Please update your code to
app.use(router);
I'm learning node.js and I have an error serving public CSS files to one URL.
It works with almost every pages, I go on the page and the css file is loaded from 127.0.0.1/css/style.css.
When the URL is 127.0.0.1/project/idProject it tries to get the css file from 127.0.0.1/project/css/style.css.
// INCLUDE MODULES =======================================================
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var Twig = require('twig');
var twig = Twig.twig;
var path = require('path');
var mongoose = require('mongoose');
var passport = require('passport');
var flash = require('connect-flash');
var configDB = require('./config/database.js');
// Assets ================================================================
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.favicon(path.join(__dirname, 'public/images/favicon.ico')));
// Start mongoose
mongoose.connect(configDB.url);
// USER MANAGEMENT =======================================================
require('./config/passport')(passport); // pass passport for configuration
app.use(express.logger('dev')); // log every request to the console
app.use(express.cookieParser()); // read cookies (needed for auth)
app.use(express.json()); // to support JSON-encoded bodies
app.use(express.urlencoded()); // to support URL-encoded bodies
app.set('view engine', 'twig'); // set up twig for templating
app.use(express.session({ secret: 'ilovescotchscotchyscotchscotch' })); // session secret
app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash())
// ROUTES =======================================================
// Set authentication variable
app.use(function (req, res, next) {
app.locals.login = req.isAuthenticated();
next();
});
require('./app/routes.js')(app, passport);
//ERROR MANAGEMENT =======================================================
app.use(app.router);
app.use(function(req, res, next){
res.status(404);
// respond with html page
if (req.accepts('html')) {
res.render('errors/404.twig', { url: req.url });
return;
}
// respond with json
if (req.accepts('json')) {
res.send({ error: 'Not found' });
return;
}
// default to plain-text. send()
res.type('txt').send('Not found');
});
/*app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.status(err.status || 500);
res.render('errors/500.twig', { error: err });
});*/
//SOCKET IO =======================================================
//Quand on client se connecte, on le note dans la console
io.sockets.on('connection', function (socket) {
console.log("New connection");
});
// LISTEN SERVER =======================================================
server.listen(80);
Any idea on how to solve this ?
Regards !
I tried approach which I saw in the comments, and because it did not work for me, I am posting an answer that worked.
All .css files are static, so you have to serve them to the client. However, you do not serve static files as a express middleware. Therefor you have to add them.
app.use(express.static(__dirname, 'css'));
Hi it was a problem for me to solve this, but with the help of salvador it was posible.
The only thing that im going to put is all the code and the you make the reference in the html, you only need to put the file not the folder in the html file.
//The index.js code
var express = require('express');
const path = require ('path');
//app va a ser mi servidor.
var app = express();
app.set('port', 3000)
//app.use(express.static('./public'));
//app.use(express.static( 'css'));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'css')));
app.listen(app.get('port'), () => {
console.log('localhost:3000')
} );
this is the structure