Routing error when using express generator - node.js

I tried using express generator by using express --ejs command.
All is good when I typed npm start in the terminal and went to http://localhost:3000/.
Now I tried adding a new route '/shop' like so:
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/*GET Shop page */
router.get('/shop', (req, res) => {
res.render('shop');
});
module.exports = router;
and add a file inside "view folder" called shop.ejs.
now, when I go to http://localhost:3000/shop there is a 404 error.
Did I miss something? I tried reading the express docs and other guides and I'm sure I didn't miss something.

Could you re-start your server.. The default npm start command doesn't automatically watch for changes.
To automatically watch for changes so you don't have to restart your server everytime, you can use nodemon
In your package.json
Add a new script/command. I'll call it dev in this case..
"scripts": {
"start": "node ./bin/www",
"dev": "nodemon ./bin/www"
},
Then start your app using
npm run dev
# or
yarn dev

Related

How run in same port Angular and Node.JS Express?

This is might be possible to duplicate question but not able to understand how to configure FE and BE together run them both.
I've gone through this and this questions, but couldn't understand.
My Node+Express running on 4300
app.post('/postData', function(req, res) {
//some worst logics here :)
});
And
Angular 5 running on 4200. Below is my FE service that calling post endpoint
postData(feData) {
console.log(feData);
this.http.post('/postData', feData, this.httpHeader).subscribe((data) => {
});
}
What I tried is opened two cmd Windows: one to run server.js by node server.js and another one with ng serve.
Result:
404 not fount(cannot post)
What am I doing wrong.
What you need to do on this case is move your Angular 5 application to run under express process. You can achieve this following this tutorial - See item 2
I removed some complications but I really recommend you to take a look on the tutorial.
npm install --save express body-parser
Create a file to run your node app like server.js and add following code:
var app = require('app.js');
var debug = require('debug')('mean-app:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '4300');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('listening', onListening);
function onListening() {
var addr = server.address();
debug('Listening on ' + port);
}
Edit "package.json" to specify how you app will start:
"scripts": {
"ng": "ng",
"start": "ng build && node server.js",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
Now, create app.js which will run express:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var sample = require('./routes/sample.js');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({'extended':'false'}));
//Put your angular dist folder here
app.use(express.static(path.join(__dirname, 'dist')));
app.use('/samples', express.static(path.join(__dirname, 'dist')));
app.use('/sample', sample);
module.exports = app;
It's a good practice to create routes folder for your elements. Create a file routes/sample.js with following content:
var express = require('express');
var router = express.Router();
router.get('/', function(req, res, next) {
res.send('RESTful API');
});
module.exports = router;
Run the server using node command:
npm start
By Experience, Keep the Backend or Microservices separate from your frontend applications.

NextJS cookie-parser middleware absent from production build

I'm developing a NextJS application and have been using npm run dev during the development process. Now I'm trying to do a production build as described on the GitHub page.
My app blows up in production mode; it seems the cookie-parser node middleware is not installed in the production build? Here is how I set it up:
server.js
const express = require('express');
const next = require('next');
const cookieParser = require('cookie-parser'); // require cookie-parser
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
const server = express();
server.use(cookieParser()); // use cookieParser
server.get('*', (req, res) => {
return handle(req, res);
});
server.listen(3000, (err) => {
if (err) throw err;
console.log('> Ready on http://localhost:3000');
});
})
.catch((ex) => {
console.error(ex.stack);
process.exit(1);
})
Later in the code I access the node req object. In development mode req.cookies is present as I would expect. In production mode it's absent.
It looks like there is no server.js file in the production build directory. What's more, grepping for cookie-parser and cookieParser in said production build directory yields empty results.
Any idea what's going on and how to get cookie-parser working in a production NextJS build?
Found the answer on the same GitHub page.
When using a custom server with a server file, for example called
server.js, make sure you update the scripts key in package.json to:
{
"scripts": {
"dev": "node server.js",
"build": "next build",
"start": "NODE_ENV=production node server.js"
}
}
One problem with the production build down!

Is it possible to start and stop the NodeJS webserver by Mocha's framework?

I'm trying to do this tutorial with one little change.
https://semaphoreci.com/community/tutorials/getting-started-with-node-js-and-mocha
I want to automatically start my webserver when the Mocha framework starts, when npm test command is executed.
I don't want to manually start the webserver, run the Mocha tests and then stop the webserver.
If I use the test command according to the tutorial, it will not start the webserver automatically:
"scripts": {
"test": "./node_modules/.bin/mocha --reporter spec"
}
This command seems to me stucked at the first stage, the tests don't run.
"scripts": {
"test": "node app/server && ./node_modules/.bin/mocha --reporter spec && ... && TERMINATE_SERVER && ..."
}
I've tried to run a js file, but in this case other problems will appear (like creating OS specific scripts)
"scripts": {
"test": "node ./test/testinit.js"
}
e.g.:
testinit.js:
if (process.platform == "linux"){
script = "testInitializer.sh"
} else { //(process.platform == "win32")
script = "testInitializer.bat"
}
after that I have to use some shell specific commands in synchronous way in my scripts:
const execSync = require('child_process').execSync;
execSync("..."); // start
// run the tests
execSync("..."); // stop
... that seems to me too complicated.
What can I do if I don't want to create multiple OS dependent solutions for this problem?
Is it possible to start and stop the webserver by the framework only when it's needed?
Thank you for your help!
I think you can do this by using supertest module. If you have a file server.js or a file creating an express app app.js, just requiring that file and passing the returned object to supertest for making http requests to your server should be sufficient.
This is an example taken from supertest documentation:
const request = require('supertest');
const express = require('express');
const app = express();
app.get('/user', function(req, res) {
res.status(200).json({ name: 'tobi' });
});
request(app)
.get('/user')
.expect('Content-Type', /json/)
.expect('Content-Length', '15')
.expect(200)
.end(function(err, res) {
if (err) throw err;
});

Angular 2 cli with Express js

I want to use express js w/ node js to be my server for an angular 2 project. I was looking at tutorials for integrating express js w/ the angular cli (I followed this and this) and I had no luck. Does anyone have any suggestions on how to do this? Currently I have a new project up w/ cli just something that says "app works!" and want to try to do it using express as opposed to using the lite server. any help is appreciated!
this link works for me, but with some changes.
I install angular-cli and create new project, then I follow the tutorial of the link but with this changes:
I create a folder called node_server
In run npm install express --save in root folder of my project. This add server like dependencie in your package.json without create new on node_server.
I create a new file in node_server called server.js, with a basic express server. This server only returns the index.html of dist folder.
Added the scripts to the package.json, the scripts are the same in the link tutorial, but with one change, the filename is server.js not index.js
This is my server.js file :
const express = require('express');
var app = express();
var staticRoot = __dirname;
app.set('port', (process.env.PORT || 3000));
app.use(express.static(staticRoot));
app.get('/', function(req, res) {
res.sendFile('index.html');
});
app.listen(app.get('port'), function() {
console.log('app running on port', app.get('port'));
});
I hope this works for you.
The above comment worked pretty well for me,
just needed to make some adjustments to the scripts in package.json suggested in that link.
"build:nodeserver": "ng build && cp node-server/* dist",
"build:nodeserver-prod": "ng build -prod && cp node-server/* dist",
"serve-build" : "npm run build:nodeserver && nodemon dist/index.js",
"serve-build-prod": "npm run build:nodeserver-prod && nodemon dist/index.js"
I have a folder called node-server
which has my server.js file like above with routes for angular2 app as above,
and some api routes in there too, and some other folders in the node-server like mysql-requests and some files like config.json file
What I do create 2 folder on is your express server (I am using
Express-generator) and 1 is Angular 2 project (Angular cli )
root folder
--->server
--->ng4
---> gulpfile.js
gulp will build your app and move build files
var gulp = require('gulp')
var rename = require("gulp-rename");
var deletefile = require('gulp-delete-file');
var exec = require('child_process').exec;
var runSequence = require('run-sequence');
gulp.task('build', function (cb) {
exec('cd ng4/ && ng build', function (err, stdout, stderr) {
cb(err);
});
})
gulp.task('rename', () => {
return gulp.src("./ng4/dist/index.html")
.pipe(rename("ng4.html"))
.pipe(gulp.dest("./server/views"));
})
gulp.task('deletefile', function () {
var regexp = /\w*(\-\w{8}\.js){1}$|\w*(\-\w{8}\.html){1}$/;
gulp.src(['./server/public/index.html',
'./ng4/dist/**/*.*'])
.pipe(deletefile({reg: regexp,deleteMatch: false}));
});
gulp.task('move', function () {
return gulp.src(["./ng4/dist/**/*.*"])
.pipe(gulp.dest("./server/public"));
});
gulp.task('default', function(callback) {
runSequence('build','rename','move','deletefile',callback)
});
In this way you can developed in ng4 app and run gulp command on root .
I have this scenario; however, I want to be able to:
run my angular CLI project using ng serve instead of modifying any gulp tasks/ processes and without having to run ng build every time
have a server-side API responding on its own port independently of the frontend -- this way the microservice architecture pattern is used and concerns between frontend and backend are separated.
To accomplish this, I used concurrently with the below package.json script modifications
"scripts": {
"start": "concurrently \"npm run-script start-frontend\" \"npm run-script start-backend\"",
"start-frontend": "ng serve",
"start-backend": "node index.js",
...
My backend index.js file is boilerplate but looks like this...
const express = require('express');
const router = express.Router();
const app = express();
const PORT = process.env.PORT || 3000;
router.get('/', (req, res) => {
res.json({ Hello: 'World' });
});
app.use('/api', router);
app.listen(PORT, function() {
console.log(`API running on port ${PORT}`);
});
Now, when I want to run the app, I can type npm start to get everything running. Then, I can go to...
http://localhost:3000/api/ to access the backend
http://localhost:4200/ to access the frontend

"Simple" RESTful API using node/mongo/express

I am completely new to server side javascript so any help would really be appreciated.
I recently followed this tutorial https://www.youtube.com/watch?v=p-x6WdwaJco to build a simple RESTful API with node.js mongodb and express. The tutorial also uses a library called node-restful https://github.com/baugarten/node-restful.
First of all I built a server.js in the root directory:
// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// Mongo DB
mongoose.connect('mongodb://localhost/rest_test');
// Express
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// Routes
app.use('/api', require('./routes/api'));
var test = require('./routes/api');
// Start Server
app.listen(3000);
console.log('API is running on port 3000')
Then I created api.js in root/routes
// Dependencies
var express = require('express');
var router = express.Router();
// Models
var Product = require('../models/product');
// Routes
Product.methods(['get', 'put', 'post', 'delete']);
Product.register(router, '/products');
// Return router
module.exports = router;
Finally I created a file called product.js within root/models:
// Dependencies
var express = require('express');
var restful = require('node-restful');
var mongoose = restful.mongoose;
// Schema
var productSchema = new mongoose.Schema({
name: String,
sku: String,
price: Number,
});
// Return model
module.exports = restful.model('Products', productSchema);
This is where my issue is(i think) - the server runs fine until I attempt to use .methods() and .register() on mongoose.Schema() from api.js. It keeps telling me that .methods is undefined in Product.
I have been through the tutorial over and over and can see nothing wrong with my code. All libraries seemed to have installed correctly. Mongo is running...
I have a feeling that mongoose.Schema is not registering properly but have no idea why as everything seems to be as it is in the tutorial - there are no similar complaints on the tutorial - so I can only assume this is "my problem" but I just can't see where I've gone wrong....
Thanks in advance....
I copied your code exactly and then was able to run it without any issues. So this most likely means there's some issue in your local environment. Most likely an old/outdated package.
In your root directory, create a file called package.json with the following contents:
{
"name": "stackoverflow-30492214",
"version": "0.0.1",
"private": true,
"scripts": {
"start": "node server.js"
},
"dependencies": {
"body-parser": "^1.12.4",
"express": "^4.12.4",
"mongoose": "^3.9.7",
"node-restful": "^0.1.18"
},
"devDependencies": {}
}
And then, in the same directory, in your terminal run npm clean && npm install. This should download/install/build dependencies as defined by the package.json. Once done, try running the server again node server.js. You might get a warning about the mongoose package being an unstable version, but you shouldn't see any .method() or .register() undefined errors.

Resources