I have this code:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
I will have many services (like the test one), and I don't want to have them all on the same file.
I read in another question in Stack Overflow, that I can require other files like this: var express = require("./model/services.js"); And in that file write all the services, but it's throwing app is not defined when I start Node.
How can I separate codes?
You can define your routes in different files say test-routes.js like this:
module.exports = function (app) {
app.get('/test', function(req, res) {
res.json(200, {'test': 'it works!'})
})
}
Now in your main file say server.js you can import your route file like this:
var express = require("express");
var app = express();
var path = require("path");
app.use(express.static(__dirname + '/public'));
app.get('/',function(req,res){
res.sendFile(path.join(__dirname+'/views/index.html'));
res.set('Access-Control-Allow-Origin', '*');
}).listen(3000);
console.log("Running at Port 3000");
// import your routes
require('./test-routes.js')(app);
your test.js should look something like:
var express = require('express');
var router = express.Router();
router.get('/test', function (req, res) {
res.json(200, {'test': 'it works!'});
});
module.exports = router;
and the app.js (assuming other is some other route defined similarly to test.js):
var test = require("./routes/test.js");
var other = require("./routes/other.js");
...
//all your code for creating app
...
app.use('/test', test);
app.use('/other', other);
Related
I am having a problem with Node.JS.
I'm trying to upload a HTML file with Node.JS (the HTML file has links to JS, JSON and CSS files) but when I turn on the server and look at the page, only what was in the HTML is written, which means there is no CSS and no JS which were working properly before I implemented the server.
Can anyone help me?
Here's the Node.JS code:
const express = require('express');
const app = express();
const port = 3000;
app.use(express.static('project-folder'));
app.get('/', function(req, res){
res.sendFile('website.html', { root: __dirname });
});
app.listen(port, function(){
console.log("server is up");
});
If your folder structure looks like this:
project-folder
|-website
| |-style.css
| |-script.js
|-website.html
|-server.js
then the code should look like this:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(path.join(__dirname, 'website')));
app.get('/', function(req, res){
res.sendFile('website.html', { root: __dirname });
});
app.listen(port, function(){
console.log("server is up");
});
if it's like this:
project-folder
|-website
| |-style.css
| |-script.js
| |-website.html
|-server.js
then the code should look like this:
const express = require('express');
const app = express();
const port = 3000;
const path = require('path');
app.use(express.static(path.join(__dirname, 'website')));
app.get('/', function(req, res){
res.sendFile('website.html', { root: path.join(__dirname, 'website') });
});
app.listen(port, function(){
console.log("server is up");
});
Mind the path module that is required at the top
Very new to express and file system and don't have much idea about directories so getting this error.
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
app.use('/public',express.static(__dirname +"/public"));
Getting error "Cannot GET /public/signup.html"
My directories is:
-Express
--Server.js
--public
---signup.html
Looks like your code is a little jumbled up. Separate out your port listener - this should always come last. Add your routes and middleware before that as individual calls to app, and also register your get request to redirect back to your server to the signup html.
This should work:
var express = require("express");
var path = require("path");
var port = 2121;
var app = express();
// Register Middlewares/Headers
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
next();
});
// Register Static
app.use("/public", express.static(__dirname + "/public"));
// Register redirect
app.get('/', (req, res) => {
res.redirect(req.baseUrl + '/public/signup.html');
});
app.listen(port, () => {
console.log("server Running on : ", port);
});
You're calling listen on app before you call use on your middleware and there are a few mistakes in your code. I think this should work:
app
.use('/public',express.static(`${__dirname}/public`))
.get('/', (req, res) => {
res.header({
'Access-control-Allow-Origin': '*'
});
res.redirect(`${req.baseUrl}/public/signup.html`);
})
.listen(2121);
You should provide
app.use('/public',express.static(__dirname +"/public"));
Before you using app.get
Full example:
var express= require('express');
var path= require('path');
var mysql= require('mysql');
var bodyParser= require('body-parser');
var app= express();
app.use('/public',express.static(__dirname +"/public"));
app.get('/', function(req, res) {
res.set( {
'Access-control-Allow-Origin': '*'
});
return res.redirect('/public/signup.html');
}).listen(2121);
console.log('server Running on : 2121');
I have the following files
app.js
var express = require('express');
var app = express();
var api = require('./routes/api');
app.use('/api/v1/', api);
routes/api.js
var express = require('express');
var router = express.Router();
var users = require('./users');
router.get('/Users', users);
module.exports = router;
routes/users.js
var express = require('express');
var router = express.Router();
router.get('/')
.get(function(req, res) {
res.send('Hello world');
});
module.exports = router;
Why doesn't this work?
I think you should customise this by using separate routes file.
app.js
var express = require('express'),
app = express(),
routes = require('./routes'); // Create a routes folder and under that create index.js
app.use('/', routes);
routes/index.js
var express = require('express'),
router = express.Router(),
apis = require('apis');
router.get('YOUR API NAME', apis.api);
router.post('YOUR API NAME', apis.ANOTHER API HERE);
Create a folder apis and put your API under apis folder also create a index.js for exporting your APIs.
apis/index.js
var APIs = ['api', 'ADD MORE APIs here'];
APIs.forEach(function(api) {
module.exports[api] = require(__dirname + '/' + api)[api];
});
hope this will help you : )
In routes/users.js
Instead of
router.get('/')
.get(function(req, res) {
res.send('Hello world');
});
Try
router.get('/',function(req, res) {
res.send('Hello world');
});
Or
router.route('/')
.get(function(req, res) {
res.send('Hello world');
});
Using router.use instead of router.get in api.js fixed it for me
Taking the following basic Express: 'Hello World' example as my starting point:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
I'm trying to organize the code in different .js files to separate configuration and routing.
This way I would have app.js:
var express = require('express');
var app = express();
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('App listening at http://%s:%s', host, port);
});
// Expose app
exports = module.exports = app;
and /routes/api.js (having api.js inside a child directory called routes):
var app = require('../app.js');
app.get('/', function (req, res) {
res.send('Hello World!');
});
but exports = module.exports = app; and var app = require('../app.js'); are not working: I get the message Cannot GET / all the time when calling the API method.
you should make app.js your 'main' file, and the routes should be inclulded in it.
your route file should look somthing like this:
var express = require('express');
var router = express.Router();
router.get('/', function (req, res) {
res.send('Hello World!');
});
module.exports = router;
and to your app.js add:
var api = require("./routes/api.js");
...
//all your code for creating app
...
app.use('/', api);
I've created a node application with express. I try to separate the following layers which will give me the ability to test the application with unit testing...
The problem is that I don't know how to call to the router.js file which will stops in the post/get/delete application.
The server.js file looks as follows
http = require('http'),
app = require('./app')(),
http.createServer(app).listen(app.get('port'), function (err) {
console.log('Express server listening on port ' + app.get('port'));
});
This is the app.js file
var express = require('express'),
logger = require('morgan'),
bodyParser = require('body-parser'),
routesApp = require('./ro/route');
module.exports = function () {
var app = express();
app.set('port', process.env.PORT || 3005);
app.use(logger('dev'));
app.use(function (req, res, next) {
res.set('APP', 'User app');
next();
});
app.use(bodyParser.json());
app.use(routesApp);
return app;
};
This is the router.js, which will route the call to other module according to the http type like post/delete/get etc...
var handleGet = require('../controller/handleGet');
var handlePost = require('../controller/handlePost');
var express = require('express');
module.exports = function (app) {
var appRoute = express.Router();
app.use(appRoute);
appRoute.route('*')
.post(function (req, res) {
handlePost(req, res);
})
.get(function (req, res) {
handleGet(req, res)
})
Currently I've two questions:
How to make it work since when in debug It dump in
app.use(appRoute); on the router.js file?
The error is TypeError: undefined is not a function
Is it good way to structure the node app like in my post? I want to seperate all this layers like SOC, I'm fairly new to node and express and I try to build it to be modular and testable...
How to make it work since when in debug It dump in app.use(appRoute); on the router.js file? The error is TypeError: undefined is not a function
This fails because you don't pass app into the module when you require it in app.js, you would need to do something like
app.use(routesApp(app)); // <- this hurts my eyes :(
Is it good way to structure the node app like in my post?I want to sperate all this leyrs like SOC,I fairly new to node and express and I try to build it to be modular and testable...
Your definitely on the right track, keeping things separated is generally always a good idea. Testing is definitely one of the big pluses but it also helps with other things like maintainability & debugging.
Personally, I would make use of the bin directory for any start up script configuration
bin/www
var app = require('./app');
app.set('port', process.env.PORT || 3005);
var server = app.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
This will help decouple your express app from all the environment setup. This should keep your app.js clean and only contain app-related config
app.js
var express = require('express')
, app = express()
, logger = require('morgan')
, bodyParser = require('body-parser')
, routes = require('./routes.js');
app.use(logger('dev'));
app.use(function (req, res, next) {
res.set('APP', 'User app');
next();
});
app.use(bodyParser.json());
app.use('/', routes);
...
module.exports = app;
Then finally, your routes.js should do nothing but handle your URLs
routes.js
var express = require('express')
, router = express.Router()
, handleGet = require('../controller/handleGet')
, handlePost = require('../controller/handlePost');
router.get('/', handleGet);
router.post('/', handlePost);
...
module.exports = router;