I have a NestJS application that starts fine with:
npm start (npm run start:prod)
or
node dist/main
However, I want to use app.js and can't figure out how to configure the app.js file to accomplish this.
app.js file
var serverType = 'AM-API-MDD';
var express = require('express');
var http = require('http');
var path = require('path');
var bodyParser = require('body-parser');
var app = express();
var port = process.env.PORT || 3030;
app.use(function(req,res,next){
res.header("Access-Control-Allow-Origin","*");
res.header("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, x-client-key, x-client-token, x-client-secret, Authorization");
next();
});
app.use(express.static(__dirname + '/dist/'));
//body parse
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ limit: '50mb',extended: true }))
// parse application/json
app.use(bodyParser.json({limit: '50mb', extended: true}))
app.all('/*', function(req, res, next) {
res.sendFile('dist/main.js', { root: __dirname });
});
// Handle 404
app.use(function(req, res) {
//res.send(‘404: Page not Found’, 404);
res.status(404).send({status:404, message: '404 Not Found', type:'client'});
});
// Handle 500
app.use(function(error, req, res, next) {
res.status(500).send({status:500, message: 'internal error', type:'internal'});
});
//listen
var httpServer = http.createServer(app);
httpServer.listen(port,() => console.log(serverType +' server running on port: '+ port));
trying to get app.js is the wrong approach.
node dist/main.js runs the application - so the startup script is the main.js file.
node-windows can reference the main.js file, rather than the app.js file.
Thanks to Jay McDoniel for pushing me in the right direction.
Related
I've been banging my head against the wall on this one for a few hours. I'm not sure why it doesn't work but it's probably something simple I'm missing. It usually is...
Anyway, I'm doing a simple HTTP PUT from Angular 7 like this:
protected put(cmd: string, body: any) {
let headers = new HttpHeaders();
headers.append('Content-Type','application/json');
console.log(body);
return this._http.put(cmd, body, {headers: headers});
}
cmd and body are being passed in. I can see the body print out in the console and the cmd path is correct to hit my route path in Node.
From there, it comes into my Node/Express app. Which goes as follows:
'use strict';
const express = require('express');
const bodyParser = require('body-parser')
// Constants
const PORT = 8080;
const HOST = '0.0.0.0';
// App
const app = express();
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// parse application/json
app.use(bodyParser.json())
app.use(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", "Origin, X-Requested-With, Content-
Type, Accept");
next();
});
app.use('/api', require('./routes/routes'));
app.use('/api/add-user', require('./routes/add-user/routes'));
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
And this is my routes file that console prints the empty body:
const express = require('express');
const router = express.Router();
const dvAdmin = require('../../controller/controller');
//Routes
//GETS
//PUTS
router.put('/addCCUser', function (req, res) {
console.log(req.body);
});
module.exports = router;
I am creating a REST api using Node.js And Express, The application works fine including routes and other functanalities on local computer but when uploaded to windows server routes are not working properly, I was able to see Hello World printed on my from home page e.g:- www.abcd.com/,
But when routes are being used eg:- www.abcd.com/users/ it gives 404 - File or directory not found.
Here is my code
server.js
const http = require('http')
const app = require('./app')
const server = http.createServer(app);
server.listen(process.env.PORT, () => {
console.log("Server Started");
});
app.js
const express = require('express');
const morgan = require('morgan');
const bodyParser = require('body-parser');
const app = express();
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use((req, res, next) => {
res.header(
'Access-Control-Allow-Origin',
'*'
);
res.header(
"Access-Control-Allow-Headers",
"Origin, X-Requested-with, Content-Type, Accept, Authorization"
);
if (req.method === 'OPTIONS') {
res.header('Access-Control-Allow-Methods', 'PUT, POST, PATCH, DELETE, GET');
return res.status(200).json({});
}
next();
});
const users_routes = require('./api/routes/users.routes');
const message_routes = require('./api/routes/message.routes');
const group_routes = require('./api/routes/group.routes');
const key_routes = require('./api/routes/key.routes');
console.log(users_routes.toString());
app.use('users', users_routes);
app.use('message', message_routes);
app.use('group', group_routes);
app.use('key', key_routes);
app.use('/', (req, res, next) => {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<H1>Hello World!</H1>');
});
module.exports = app;
user.routes.js
const express = require('express');
const router = express.Router();
router.get('/', (req, res, next) => {
Console.log("Hello there");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<H1>Hello World!</H1>');
});
module.exports = router;
Log file after starting app
Server Started
It prints function when used typeof(user_routes)
Having issues with the express router
I'm getting a 404 for the login route, so it must be how I've initialised my routes?
I'm not handling "/" but I'm not sure how to??
My index file:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var blogRoutes = require('./routes/blogs');
var loginRoute = require('./routes/login');
var port = process.env.PORT || '3000';
var http = require('http');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
mongoose.connect(myInfo);
app.set('view engine', 'hbs'); //Templating engine (HandleBars)
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(function(req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
res.setHeader('Access-Control-Expose-Headers', 'Authorization');
res.setHeader('Access-Control-Allow-Methods', 'POST, GET, PATCH, DELETE, OPTIONS');
next();
});
//ROUTES
//Handle specific routes first
app.use('/blogs', blogRoutes);
app.use('/login', loginRoute);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
return res.render('404');
});
module.exports = app;
my login.js Just a simple logging for now:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
console.log("LOG::::::::::::::::::::::::::")
});
And in Angular:
login(email, password) {
return this.http.post(this.blogsURL + 'login', {email:email, password:password} )
.map((res) => {
console.log(res)
return res;
})
Any pointers?
You are sending a POST call to a GET route /login.
(I'm sorry. I don't have enough reputation to comment.)
Apologies, I made a noobie error and didn't subscribe to the login function in the component
this.authService.login(email, password)
.subscribe(data=>console.log(data));
Thanks for your help
I'm building a Q&A app following this tutorial and everything goes well, but I need to change the chance to change the base root where the app is being served via config files.
Now the app is served in localhost:8080 and I need to be served over localhost:8080/qae (for example).
I think the answer is near this piece of code:
// Setup server
var app = express();
var server = http.createServer(app);
var socketio = require('socket.io')(server, {
serveClient: config.env !== 'production',
path: '/socket.io-client'
});
require('./config/socketio')(socketio);
require('./config/express')(app);
require('./routes')(app);
// Start server
function startServer() {
app.angularFullstack = server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode '+config.ip, config.port, app.get('env'));
});
}
setImmediate(startServer);
(from /server/app.js)
But I can't figure it. Is it possible doing this in a simple way?
////////EDIT////////
I tried all the proposed solutions, but I'm doing something wrong and got errors. This is my routes.js in case it helps:
/**
* Main application routes
*/
'use strict';
import errors from './components/errors';
import path from 'path';
export default function(app) {
// Insert routes below
app.use('/api/cpd', require('./api/cpd'));
app.use('/api/categories', require('./api/category'));
app.use('/api/terms', require('./api/term'));
app.use('/api/qae', require('./api/qae'));
app.use('/api/stats', require('./api/stat'));
app.use('/api/tags', require('./api/tag'));
app.use('/api/questions', require('./api/question'));
app.use('/api/things', require('./api/thing'));
app.use('/api/users', require('./api/user'));
app.use('/auth', require('./auth'));
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");
next();
});
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
}
You can do the following:
var app = express();
var routes = require('./routes/index');
app.set('base', '/qae');
then you need to add route
app.use('/qae', routes);
Hope this helps :)
You should change your rooting to this:
app.use('/qae',require('./routes'))
and in routes/index.js you can have all declarations of your routes.
In routes.js
export default function(app) {
// Insert routes below
app.use('/qae', require('./api'));
app.use('/auth', require('./auth'));
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");
next();
});
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get((req, res) => {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
}
create file index.js in api
const express = require('express')
const router = express.Router()
router.use('/api/cpd', require('./cpd'));
router.use('/api/categories', require('./category'));
router.use('/api/terms', require('./term'));
router.use('/api/qae', require('./qae'));
router.use('/api/stats', require('./stat'));
router.use('/api/tags', require('./tag'));
router.use('/api/questions', require('./question'));
router.use('/api/things', require('./thing'));
router.use('/api/users', require('./user'));
module.exports = router
That way all your api routes will look like /qae/api/*. If you need auth also after this prefix you need to do it same way.
Best solution is to have i app.use('/',...) including routers from subfolders.
If your ./routes module returned a router instead of taking an app object, then you could do this to make it available in / route:
app.use(require('./routes'));
or this to use /qae prefix:
app.use('/qae', require('./routes'));
but since you pass the app object to the function exported by ./routes then it is the ./routes module that actually registers the routes and since you didn't include its code it's hard to give you a specific example. I can only say that you will need to change the routes definitions in ./routes for a different prefix, and you'd need to return a router instead of taking app argument for the above examples to work.
Tthen you ./routes would have to look like this:
let express = require('express');
let router = express.Router();
router.get('/xxx', (req, res) => {
// ...
});
router.get('/yyy', (req, res) => {
// ...
});
module.exports = router;
and only then you'll be able to use:
app.use('/qae', require('./routes'));
in the main code.
Folder Structure
bin/
www
server/
routes/
index.js
book.js
views/
index.ejs
app.js
router.js
error.js
public/
package.json
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 app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
// 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')));
require('./router')(app);
require('./errors')(app);
module.exports = app;
route.js
var index = require('./routes/index');
var books = require('./routes/books');
var base = '/api';
module.exports = function (app) {
app.use(base+'/', index);
app.use(base+'/books', books);
};
error.js
module.exports = function (app) {
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// 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
app.use(function (err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
};
index.js
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
module.exports = router;
I've got problemas with Backbone.history.start({pushState: true}); when is actived
I use the backbone router 'example/:id':'test' and the browser returns me an error
GET myhost:1337/example/js/views/test.js 404 (Not Found)
I want to rotate with Backbone for example myhost:1337/example/test without the necessity to request nodejs.
si, I dunno why,
Could be my server Nodejs?
Or Could be my code that it's not well written?
Thanks in advance
MY server code is
//var http = require('http');
var path = require('path'),
express = require('express'),
routes = require('./routes/index'),
http = require('http'),
app = require('express')();
app.configure(function(){
//app.set('view options',{layout: false });
app.set('port', process.env.PORT || 1337);
app.use(express.bodyParser()),
app.use(express.static(path.join(__dirname, 'public')));
app.use(app.router); // you need this line so the .get etc. routes are run and if an error within, then the error is parsed to the ned middleware (your error reporter)
app.use(function(err, req, res, next) {
if(!err) return next(); // you also need this line
console.log("error!!!");
res.send("error!!!");
});
});
app.get('*',function(req,res){
res.setHeader('content-type', 'text/javascript');
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.redirect('http://localhost:1337#'+req.url);
});
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
});
This is something with your server. I'm willing to bet you didn't hold the shift key down when you typed out your route, so you have something like this in your server
app.get('example?:id':'test', function() {});
When you should have:
app.get('example/:id':'test', function() {});
This block:
app.post('/addPlace?:?',routes.addPlace);
app.get('/searchPlace?:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById?:id',routes.showPlaceById)
app.post('/deletePlace?:?',routes.deletePlace);
See the ?'s everywhere? This should really be:
app.post('/addPlace',routes.addPlace);
app.get('/searchPlace/:q',routes.searchPlace);
app.post('/showPlace',routes.showPlace);
app.get('/showPlaceById/:id',routes.showPlaceById)
app.post('/deletePlace',routes.deletePlace);
If you change that, /showPlaceById/:id will return what you expect.