ExpressJS not call ajax get method - node.js

I created a sample ExpressJS App by using Express Application Generator
I want to call localhost:3000/data to get some data. I added these code to app.js:
app.get('/data', function(req, res){
debug("get data");
});
Also I make ajax request in client side js file :
$.ajax({
url: 'http://localhost:3000/data/',
//url: 'http://localhost:3000/data', -> also not work
type:'GET',
dataType: 'json',
success: (data) => {
console.log("get data from client js", data);
}
});
but my app.get method never call. GET /data/ 404 written in console screen. Also when I typed http://localhost:3000/data on browser I got Not Found error. how can I fix this ?
my www file :
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('myapp: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'm not exactly sure where your problem lies because there isn't enough code displayed to determine that. instead I have written a simple express server for you to use:
const express = require('express');
const bodyParser = require('body-parser');
const CORS = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(CORS());
app.get('/data', (req, res) => {
res.json({message: "working"});
});
app.listen(5000, () => {
console.log('Server listening on port 5000');
});

Related

Accessing Node server remotely from React page

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.

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.)

Socket.io not working in node.js express

I made an app with express generator, I'm using socket.io in my app but it's not working for me. I use socket.io in bin/www file and after the server created and listened to the port. after load the page that want to connect to the socket, browser's console show this error:
'socket.emmit is not a function'
here's the codes:
var app = require('../app');
var debug = require('debug')('server3:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '8585');
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
return val;
}
if (port >= 0) {
return port;
}
return false;
};
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;
debug('Listening on ' + bind);
};
var io = require('socket.io').listen(server);
io.on('connection', function(socket){
console.log('socket is on...');
});
It's the summary of my socket codes. the main codes are here. anyway it's not working!
The proper name of the method is socket.emit (single "m").

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.

Express and Cluster node modules in the same app

I am creating an app that allows users to upload files in their browsers to a server.
I started it by typing express in the folder of my project. With that express created all the folders and such. It created a bin folder containing a www file that starts a lot of stuff for us like the ports.
At first i only had one core so i was doing it like so:
var express = require('express');
var multer = require('multer');
var app = express();
var done = false;
var fileSize = 0;
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename){
return filename;
},
onFileUploadStart: function(file){
console.log(file.originalname + ' is starting...');
},
onFileUploadComplete: function(file){
console.log(file.fieldname + ' uploaded to ' + file.path);
done = true;
},
onFileUploadData: function(file, data){
fileSize += data.length;
console.log("FileUpload " + fileSize);
}
}));
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
app.post('/upload/', function(request, response){
console.log(request.body);
if (done == true)
response.end('file uploaded');
});
module.exports = app;
Eventually i needed to user a machine with several cores in order to be able to respond to more client requests. So I am trying to use the cluster module.
I changed the code accordingly:
var cluster = require('cluster');
if(cluster.isMaster){
var numCPUS = require('os').cpus().length;
for(var i=0; i<numCPUS; i++)
cluster.fork();
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
cluster.on('online', function(worker) {
console.log('worker ' + worker.process.pid + ' started');
});
}else{
var express = require('express');
var multer = require('multer');
var app = express();
var done = false;
var fileSize = 0;
app.use(multer({ dest: './uploads/',
rename: function (fieldname, filename){
return filename;
},
onFileUploadStart: function(file){
console.log(file.originalname + ' is starting...');
},
onFileUploadComplete: function(file){
console.log(file.fieldname + ' uploaded to ' + file.path);
done = true;
},
onFileUploadData: function(file, data){
fileSize += data.length;
console.log("FileUpload " + fileSize);
}
}));
app.get('/', function(request, response){
response.sendFile(__dirname + '/index.html');
});
app.post('/upload/', function(request, response){
console.log(request.body);
if (done == true)
response.end('file uploaded');
});
module.exports = app;
}
The problem is that when i do this i am getting the following error in the console:
Run: node ./bin/www
Result:
app.set('port', port);
TypeERror: Cannot call method 'set' of undefined at Object.<anonymous>
This happens since i placed the entire code inside the forked childs of the master. Anyone knows why this happens and how i can fix it?
EDIT:
In here you can see the bin/www file where the port and some other configurations are set:
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
var debug = require('debug')('dropbox: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);
}

Resources