Accessing Node server remotely from React page - node.js

I have created a site using Create React App on the frontend and Node express on the back. I then hosted React on IIS and ran Node as a windows service on the backend.
When running the app I set my callback paths in React (REACT_APP_HOST) to "localhost" and in the node my routes are "/routeName". This being said, the first path called is ${REACT_APP_HOST}/sitemap and the receiving path on the server is router.use('/siteMap', (req, res, next) => siteMapController(req, res, next));.
On the local server, using it as a client, this works perfectly. On a remote client (same domain) I am getting a 404 error.
The next step I tried was changing REACT_APP_HOST to "", making the resulting call to "/sitemap". This has stopped the functioning even on localhost.
Here is my code (app.js, sitemap fetch and server.js). Hoping that someone can give me a clue as to where I am going wrong.
//app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser')
var logger = require('morgan');
var cors = require('cors');
var nodeSSPI = require('express-node-sspi');
let routeList = require('./routes/routeList');
let FileLoader = require('./Controllers/FileLoader');
var app = express();
app.use(bodyParser.json({ limit: '400000' }));
app.use(cors({
origin:['http://localhost', 'http://intranet-test', 'http://intranet'],
credentials: true
}));
app.use(express.static(path.join(__dirname,'../public')));
app.options('*', cors()); // include before other routes
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
//https://www.npmjs.com/package/yarn
app.use(nodeSSPI({
retrieveGroups: false,
offerBasic: false,
authoritative: true,
}));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
routeList(app);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
console.log(req.originalUrl);
console.log(req.method)
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
console.log(err);
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
//sitemap fetch
export const fetchInit = () => {
return ({
method: 'GET'
, headers: {
'Content-Type': 'application/json'
}
, credentials: 'include'
})
};
export const Sitemap_Fetch = () => (dispatch) => {
dispatch({
type: ActionTypes.SITEMAP_LOADING
});
var myReq = new Request(`${process.env.REACT_APP_HOST}/siteMap`, fetchInit());//?' + params
return fetch(myReq)
.then((response) => {
// if (response.ok) {
return response;
// }
// else {
// var error = new Error("Error " + response.statusText);
// error.response = response;
// throw error;
// }
},
(error) => {
var err = new Error(error.message);
throw err;
}
)
.then(response => response.json())
.then((data) => {
try {
dispatch({
type: ActionTypes.SITEMAP_LOADED,
payload: data
})
return data;
}
catch (ex) { throw ex }
})
.catch((err) => {
return dispatch({
type: ActionTypes.SITEMAP_FAILED,
payload: err.message
})
});
}
//server.js
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('./app');
var debug = require('debug')('node-backend:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort('3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port, '0.0.0.0');
server.on('error', onError);
server.on('listening', onListening);
server.on('request',test=>{console.log(test)})
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
console.log(addr)
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
console.log('Listening on ' + bind);
}
Finally I am adding the .env file from my React site
BROWSER=none
SKIP_PREFLIGHT_CHECK=true
REACT_APP_HOST=http://localhost
PORT=80
This works as is. When I change REACT_APP_HOST to nothing it stops functioning.
THanks.

What I have done to solve this is use the serve (https://stackoverflow.com/a/49209041/2242131) command from a simple batch file and run my node backend from another batch. Then in React I created a constant called "hostname" which I set to ${window.location.hostname}:3000. This is now consistently serving my pages the necessary data.

Related

WebSocket with Express - Invalid WebSocket frame: invalid UTF-8 sequence

I'm building a web application using HTTPS, Express, Socket.io, and WebSocket. Currently Express is using port 3000. In order to use the same port of WebSocket as 3000 port, I wrote the code as follows.
app.js
const path = require('path');
const express = require('express');
const app = express();
const mainRouter = require('./routes/main/main');
// Middleware
...
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'res')));
app.use('/', mainRouter);
// 404 error handler
app.use((req, res) => {
logger.error(`404 Page not found`);
res.status(404).send('404 Page not found');
});
module.exports = app;
bin/www
const fs = require('fs');
const path = require('path');
const app = require('../app');
const https = require('https');
const options = {
key: fs.readFileSync(path.resolve(__dirname, '../config/ssl/localhost-key.pem')), // Private key
cert: fs.readFileSync(path.resolve(__dirname, '../config/ssl/localhost.pem')), // Certificate
};
const server = https.createServer(options, app);
const io = require('socket.io')(server);
const WebSocket = require('../public/js/websocket');
const normalizePort = (value) => {
const port = parseInt(value, 10);
if(isNaN(port)) {
return value;
}
if(port >= 0) {
return port;
}
return false;
};
const port = normalizePort(process.env.PORT || 3000);
// Setting port
app.set('port', port);
const onError = (err) => {
if(err.syscall !== 'listen') {
throw err;
}
const bind = typeof(port) === 'string' ? `Pipe ${port}` : `Port ${port}`;
switch(err.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
};
const onListening = () => {
const address = server.address();
const bind = typeof(address) === 'string' ? `Pipe ${address}` : `Port ${port}`;
};
...
WebSocket(server);
server.listen(port, '0.0.0.0');
server.on('error', onError);
server.on('listening', onListening);
public/js/websocket.js
const ws = require('ws');
module.exports = function WebSocket(server) {
const wss = new ws.Server({ server : server });
wss.on('connection', (ws, req) => {
ws.on('message', (data) => {
ws.send(data);
console.log(data);
});
});
wss.on('listening', () => {
console.log('listening..');
});
};
routes/main/main.js
const router = require('express').Router();
const { v4 : uuidv4 } = require('uuid');
router.get('/', (req, res) => {
res.redirect(`/${uuidv4()}`);
});
router.get('/:room', (req, res) => {
res.render('main/main', { room: req.params.room });
});
module.exports = router;
After configuring the server as above, if you connect to https://localhost:3000 after npm start, the following error occurs.
Error: Invalid WebSocket frame: invalid UTF-8 sequence ... code: 'WS_ERR_INVALID_UTF8', [Symbol(status-code)]: 1007
I don't understand why this error occurs. Also, how can I fix the code to fix the error?

After refresh "Cannot set headers after they are sent to the client"

I am using express js, mongoose and ejs as templates.
When I refresh my page, in second or third try, I get this error.
Here is my app.js :
{consts..}
var index = require('./routes/index.js');
var users = require('./routes/users.js');
app.set("port", ("2401"));
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use('/', index);
app.use('/users', users);
var port = '2401';
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
console.log('server started on port : ' + app.get('port'));
}
users router :
{consts..}
router.get('/login', function (req, res) {
users.getLogin(req, res);
});
router.post('/login', [
check('email')
.isEmail().withMessage('Please enter a valid email address')
.trim()
.normalizeEmail(),
check('terms', 'Please accept our terms and conditions').equals('yes'),
],
function (req, res) {
users.postLogin(req, res);
});
module.exports = router;
and controller :
usersController.getLogin = function (req, res) {
const connector = mongoose.connect(conStr, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('open', function (ref) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
}
else {
return res.render("../views/login.ejs", {
_: _,
categories: cats
});
}
});
});
}
index router :
var express = require('express');
var router = express.Router();
var index = require("../controllers/indexController.js");
router.get('/', function (req, res) {
index.list(req, res);
});
module.exports = router;
index controller:
var mongoose = require("mongoose");
var categories = require("../models/categories.js");
var _ = require("underscore");
var indexController = {};
indexController.list = function (req, res) {
const connector = mongoose.connect(conStr, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.connection.on('open', function (ref) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
}
else {
console.log("indexe geldi");
return res.render("../views/index.ejs", {
_: _,
categories: cats,
sess: req.session
});
}
})
})
};
module.exports = indexController;
I tried almost everything but still no progress. Can it be about usage of "next()" ?
I also tried the hole router get / post functions with next, mongoose find functions with exec().
The issue is that you're opening a connection to mongo in every route and:
mongoose.connection.on('open' is firing for past requests, requests that are already finished, that's why you're getting Cannot set headers after they are sent to the client.
Move the mongoose.connect & the listener outside of each route.
usersController.getLogin = function (req, res) {
categories.find(function (err, cats) {
if (err) {
console.log("Error:", err);
return res.status(500).send('error');
}
else {
return res.render("../views/login.ejs", {
_: _,
categories: cats
});
}
});
}

babel-node, cannot get server to listen on port

I am currently trying to run node es6 with babel on a docker container and am running into some issues getting the app to start listening on port 3000. I can see where the app.js file is being processed as I am seeing the database connection code running. The problem seems to be even though app.js is getting called I am not seeing anything from /bin/www getting called which would result in the server listening on port 3000.
This is the command that is getting called to start the container:
nodemon ./bin/www -L --exec babel-node --inspect=0.0.0.0:56745
app.js:
……
(async () => {
try {
console.log('about to start the database connection... - 1');
mongoose.set('useCreateIndex', true);
mongoose.Promise = global.Promise;
console.log('about to start the database connection... - 2');
setTimeout(async () => {
await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
}, 60000);
//await mongoose.connect(process.env.DB_HOST, {useNewUrlParser: true});
console.log('about to start the database connection... - 3');
let db = mongoose.connection;
console.log('about to start the database connection... - 4');
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
console.log('about to start the database connection... - 5');
} catch (e) {
console.log('We have an error.....');
console.log(e);
}
})()
let app = express();
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(helmet());
app.use(methodOverride());
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/group', groupsRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use((err, req, res, next) => {
if (process.env.NODE_ENV === "development") {
app.use((err, req, res, next) => {
if (err instanceof NotFoundError) {
//res.status(404).send(err.message);
res.statusCode = 404;
return res.json({
errors: [err.stack]
});
} else {
//res.status(500).send('An error occurred while processing your request.');
res.statusCode = 500;
return res.json({
errors: [err.stack]
//errors: ['An error occurred while processing your request.']
});
}
});
}
// production error handler
// no stacktraces leaked to user
console.log('about to begin configurations..... 7');
if (process.env.NODE_ENV !== "development") {
app.use((err, req, res, next) => {
if (err instanceof NotFoundError) {
//res.status(404).send(err.message);
res.statusCode = 404;
return res.json({
errors: [err.stack]
});
} else {
//res.status(500).send('An error occurred while processing your request.');
res.statusCode = 500;
return res.json({
errors: [err.stack]
//errors: ['An error occurred while processing your request.']
});
}
});
}
});
module.exports = app;
/bin/www:
#!/usr/bin/env node
/**
* Module dependencies.
*/
let app = require('../app');
let debug = require('debug’)(‘myapp:server');
let http = require('http');
/**
* Get port from environment and store in Express.
*/
let port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
let server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
const normalizePort = (val) => {
debug('port = ' + val);
let port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
const onError = (error) => {
debug('Houston we have a problem');
if (error.syscall !== 'listen') {
throw error;
}
let bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
const onListening = () => {
debug('Listening');
let addr = server.address();
let bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
.babelrc:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "transform-async-to-generator"]
}
Update:
The issue seems to be with node and the arrow operator. When I changed to the function keyword, it started working. I added the following to my .bablerc file:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "transform-async-to-generator", "transform-es2015-arrow-functions"]
}
but it is still an issue. How can I use the arrow operator with nodejs?
If you aren't able to progress past the normalizePort call, are you sure it exists at that time?
You need to move the definition of the function above the place you use it.
(If you are used to old, pre-ES6 "function hoisting" using vars and functions, you should note that that does not work with const and let statements.)

Can't establish a connection to the server with websockets

I am doing a MEAN stack application. To communicate between the client and the server I use some HTTP requests and websockets.
On the localhost it works fine.
But then, when I try to deploy the application from localhost to a specific server, the websockets are not working anymore. However, http requests work fine.
I got this error:
Firefox can't establish a connection to the server at
ws://138.250.31.29:3000/socket.io/?userId=5b7c030dca40486dabaafaaf&EIO=3&transport=websocket&sid=oEcoYYbhD4ighJC0AAAB.
I didn't succeed to have more information about this error.
In order to establish the connection I have two files on Node.JS:
APP.JS
const createError = require("http-errors");
const express = require("express");
const path = require("path");
const logger = require("morgan");
const favicon = require("serve-favicon");
const cors = require("cors");
require("./models/db");
require("./config/passport");
const passport = require("passport");
const apiRouter = require("./routes/index");
const corsOptions = {
origin: "*",
optionsSuccessStatus: 200
};
const app = express();
app.use(logger("dev"));
app.use(express.json({ limit: "1gb" }));
app.use(express.urlencoded({ extended: false }));
app.use(passport.initialize());
app.use(cors(corsOptions));
app.use("/api", apiRouter);
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, POST, PUT, DELETE, OPTIONS");
next();
});
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
// render the error page
res.status(err.status || 500);
res.render("error");
});
// error handlers
// Catch unauthorised errors
app.use(function(err, req, res, next) {
if (err.name === "UnauthorizedError") {
res.status(401);
res.json({ message: err.name + ": " + err.message });
}
});
module.exports = app;
WWW
!/usr/bin/env node
/**
* Module dependencies.
*/
const app = require("../app");
const debug = require("debug")("sorfml:server");
const http = require("http");
const socketIO = require("socket.io");
/**
* Get port from environment and store in Express.
*/
const port = normalizePort(process.env.PORT || "3000");
app.set("port", port);
/**
* Create HTTP server.
*/
const server = http.createServer(app);
/**
* Bind the socket.IO with the http server
*/
const io = socketIO(server);
io.origins("*:*");
clientsList = {};
/**
* Socket connection
*/
io.on("connection", socket => {
console.log("Client connected " + socket.id);
socket.user_id = socket.handshake.query.userId;
clientsList[socket.handshake.query.userId] = socket;
socket.on("disconnect", () => {
delete clientsList[socket.user_id];
console.log("Client disconnected: " + socket.id);
});
});
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on("error", onError);
server.on("listening", onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
const port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
const bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
const addr = server.address();
const bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
console.log("Listening on " + bind);
}
On the client side:
import * as io from "socket.io-client";
private socket;
this.socket = io("http://138.250.31.29:3000", { query: "userId=" + userId });
this.socket.on("sendNotification", data => {
// Do a function
});
this.socket.on("deleteNotificationFromAuthor", data => {
// Do a function
});
You are using http instead of ws on client side,
this.socket = io("ws://138.250.31.29:3000", { query: "userId=" + userId });
FYI: In case you didn't knew, both http and ws port may be the same as the w3 standard. You should use ws protocol to create a web socket connection
Hope that helps.

node.js express generator app not responding

The only file/folder ive changed is the main app.js after i installed express generator and npm install. Im a newb, maybe its its a typo in the app.js file. Heres the file and console output. Thanks so much. when i go to localhost:3000 on chrome it says cannot GET/ and it failed to load resource in console 404 and on the comm line it says GET / 404 11.960 ms - 13 everytime i reload the page
^Cryan#\Ryan:~/Desktop/node/frameworks/expressapi$ npm start
> expressapi#0.0.0 start /home/ryan/Desktop/node/frameworks/expressapi
> node ./bin/www
curl -X get http://localhost:3000/products
curl -X DELETE http://localhost:3000/products/2
and the app.js file
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 routes = require('./routes');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// 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')));
var products = [
{
id: 0,
name: 'watch',
description: 'tell time with this amazing watch',
price: 30.00
},
{
id: 1,
name: 'sandals',
description: 'walk in comfort with these sansdals',
price: 10.00
},
{
id: 2,
name: 'watch',
description: 'protect your eyes!',
price: 25.00
}
];
app.get('./routes');
app.get('/products', function(req, res) {
res.json(products);
});
app.get('/products/:id', function(req, res) {
if (req.params.id > (products.length - 1) || req.params.id < 0) {
res.statusCode = 404;
res.end('NotFound');
}
res.json(products[req.params.id]);
});
app.post('/products', function(req, res) {
if (typeof req.body.name === 'undefined') {
res.statusCode = 400;
res.end('a product name is required');
}
products.push(req.body);
res.send(req.body);
});
app.put('/products/:id', function(req, res) {
if (req.params.id > (products.length - 1) || req.params.id < 0) {
res.statusCode = 404;
res.end('not found');
}
products[req.params.id] = req.body;
res.send(req.body);
});
app.delete('/products/:id', function(req, res) {
if (req.params.id > (products.length - 1) || req.params.id < 0) {
res.statusCode = 400;
res.end('not found for that id');
}
products.splice(req.params.id, 1);
res.json(products);
});
module.exports = app;
and here iis the www file
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('expressapi:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
I run your code and it looks fine. It does not have a route for "/", so you will get a Cannot GET / message in the browser if you enter http://localhost:3000/
http://localhost:3000/products returns your JSON data correctly.
For the curl command you have to use GET in capital letters:
curl -X GET http://localhost:3000/products
[{"id":0,"name":"watch","description":"tell time with this amazing watch","price":30},{"id":1,"name":"sandals","description":"walk in comfort with these sansdals","price":10},{"id":2,"name":"watch","description":"protect your eyes!","price":25}]
If you want to add the default '/' route from express generator, change your app.js file on line with this code:
var routes = require('./routes/index');
And then add the following line later on in the code:
app.use('/', routes);
You will then see the Welcome to Express message when you point your browser to http://localhost:3000
I hope that helps clarify.

Resources