When running my application through Grunt serve on another machine although the application loads, the information from Mongo and node do not load:
Error message
Here is my server code:
//Loading requiriments
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var _ = require('lodash');
// Starting application
var app = express();
// Middleware for REST API
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride('X-HTTP-Method-Override'));
// CORS (cross domain refference) Support
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.use('/hello', function(req, res, next) {
res.send('Hello Robin');
})
// connecting to MongoDB
mongoose.connect('mongodb://localhost/tvapp');
mongoose.connection.once('open', function() {
// Load models
app.models = require('./models/index');
// Load the routes.
var routes = require('./routes');
_.each(routes, function(controller, route) {
app.use(route, controller(app, route));
});
//log server action
console.log('Listening to port 3000');
// Listen on port defined
app.listen(3000, '127.0.0.1');
});
Does anyone have any idea on what I might have done wrong?
I am using yeoman as well, would that be an issue?
Also, on my machine works fine, it won't work on outside machines which have access to the application and the server separately however the application won't run the server
The IP host address you are using is localhost, i.e., 127.0.0.1. This IP is only available to the computer it is running on. For other computers to access your server, you will have to use another IP host. If it is on the same local network, you can use your LAN IP. If not, you will have to use your public IP. How you go about finding your LAN or public IP address will depend on your operating system.
Related
I have a pretty simple nodejs project that uses express. When I start this project locally I have noticed that something is calling a POST to /inform about every 30 seconds. I'd like to know what's calling inform and what the purpose is.
I'm new to node. Is this normal? I haven't implemented a route for this call so it causes a 404.
Here's my main app:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const fileUpload = require('express-fileupload');
const app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
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(fileUpload());
// routes
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use((req, res, next) => {
console.log(req)
next(createError(404));
});
// error handler
app.use((err, req, res) => {
// 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');
});
// Start the server
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
console.log('Press Ctrl+C to quit.');
});
In my console, I see this about every 30 seconds:
POST /inform 404 14.002 ms - 2158
POST /inform 404 13.910 ms - 2158
POST /inform 404 31.536 ms - 2158
EDIT:
Thank you for the comments. I changed my express port to 8000 and it no longer happens. So something on my local machine is looping and posting to localhost:8080/inform. I'll have to trace this down.
I have a Ubiquity Unify network stack at home. After running (and stopping) the Unifi Controller on my laptop, all my Unify devices continue to send a POST <laptop IP>:8080/inform.
My own application was getting its logged filled up with the same unknown route: "/inform" error.
Solutions:
Choose a different port
Bind your application to 'localhost' instead of '0.0.0.0'
Get a dedicated controller device, like a Raspberry Pi or Unifi Cloud Key
This could be pretty much any application on your PC or even other systems in your local network, if you are listening on public addresses.
You could implement the route to see if the request header/body give any hint as to where this is coming from.
It may also be possible for external software such as Wireshark to monitor network calls to localhost, including their source.
Otherwise use a different port where no one is sending periodic pings to.
I need to create a NodeJS application which serves only for exposing REST APIs. When I created a ExpressJS project using Express generator express myNodeApp, it creates a project defaulting the view to .jade files.
Can I create and run a NodeJS project without views ? My NodeJS project will expose REST services which another client application will consume. Hence my NodeJS project do not need any UI elements. Also what package.json or .bin/www file will have. I will be hosting my NodeJS project in Azure cloud and my client application will consume the exposed service from cloud.
For an example see the code in this answer:
Node.js send data to backend with AJAX
Stripping all unnecessary code it would be basically:
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.post('/email', (req, res) => {
console.log(req.body.address);
res.json({ ok: true });
});
app.listen(4443, () => console.log('Listening on http://localhost:4443/'));
This code is a very simple REST API that exposes one endpoint but you can easily add more.
But if you're building a RESTful API from scratch then you can consider using some other frameworks like: Hapi, Restify, LoopBack, and other frameworks listed on http://nodeframework.com/ - Express is a very solid but fairly minimal framework and it's not the only option out there.
Yes you can. express is capable to return response other that html element.
However, I would recommend you to use swagger project in developing REST API via express. The project will surely come in handy when developing and MAINTAINING API, especially if your API is huge and complex (lots of url and operation).
This site has a good explanation on how to install, use and run the swagger in NodeJs.
You can do this with express - see below
Install express and body-parser, feel free to use the module below
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
module.exports = {
init: function(module_Enabled){
var portnum = 1234; process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
var allowCrossDomain = 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', 'Content-Type, Authorization, Content-Length, X-Requested-With');
// intercept OPTIONS method
if ('OPTIONS' == req.method) {
res.send(200);
} else {
next();
}
};
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(allowCrossDomain);
var server = app.listen(portnum, function() {
var host = server.address().address;
var port = server.address().port;
console.log("Content Provider Service listening at http://%s:%s", host, port);
});
app.get('/', function(req, res) {
res.send('data');
});
}
}
I have a NodeJS app I am using as a game server.
I am trying to setup CORS with it, but app.use doesn't seem to be getting called.
Anyone know why?
var util = require("util"); // Utility resources (logging, object inspection, etc)
var fs = require('fs');
var express = require("express");
var app = express();
var port = 3000;
app.use(function (req, res, next) {
// these never get printed out:
util.log( "app.use adding Access-Control-Allow-Origin" );
console.log( "app.use adding Access-Control-Allow-Origin" );
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'https://example.com');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
// Pass to next layer of middleware
next();
});
var server = app.listen(port, function(){
console.log('CORS-enabled web server listening on port ' + port);
});
var io = require('socket.io').listen(server);
Checkout the npm cors package. https://www.npmjs.com/package/cors
Example usage where all requests will be CORS enabled:
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
app.get('/my_API_URL/:id', function(req, res, next){
res.json({msg: 'This is CORS-enabled for all origins!'});
});
app.listen(80, function(){
console.log('CORS-enabled web server listening on port 80');
});
On their page they also got other examples where the CORS are only enabled on a single route.
Also, just wondering how are you testing your application? You haven't defined any routes in the example code.
As pointed out in the comment section, #Nitzan Wilnai is not doing REST API, apologise for the confusion. It is suppose to be a simple server that listens on a certain port, so for this case you might not need express at all. Did some research and this solution came out;
io.configure('development', function(){
io.set('origins', '*:*');
}
OR
io.set( 'origins', '*domain.com*:*' );
References:
Socket.io doesn't set CORS header(s)
Just in case you are trying to build a chat program. Here is an example project;
https://github.com/socketio/socket.io
What's the best way to reject requests to my web server (running via Node express) that are coming in to an unrecognized hostname? I.e. I only want to respond to requests that are intended for my domain, not for requests that are just aimed at my IP address.
The easiest way would probably be to use the connect vhost middleware.
Where you would normally do this:
var app = express();
app.get('/', function(req, res){
res.send('HI');
});
app.listen(80);
You would do this:
var vhostApp = express();
vhostApp.get('/', function(req, res){
res.send('HI');
});
var app = express();
app.use(express.vhost('example.com', vhostApp));
app.listen(80);
I am inside a middleware (function(req, res, next) {...}).
Is there a way to access the HTTP server object from the req?
UPDATE
Let me be more specific. I am trying to find out a port that the server listens on, or unix socket path, if it's listening on that.
How about in your main app file:
var express = require('express');
var http = require('http');
var app = express();
app.use(app.router);
app.get('/', function (req, res, next) {
console.log(req.socket.server);
});
app.server = http.createServer(app);
app.server.listen(3000);
As Brad mentioned, Express does expose something resembling the object returned from #createServer(), however, TJ has been giving serious consideration to dropping any inclusion of the HTTP module in express in future releases. Using the code above will be future safe.
If what you are trying to do is expose the server object inside your routers, then yeah, middleware is the way to go:
var express = require('express');
var http = require('http');
var app = express();
var server = http.createServer(app);
app.use(function(req, res, next){ //This must be set before app.router
req.server = server;
next();
});
app.use(app.router);
server.listen(3000);
The middleware is used to expose the server object. Then, you can just access it in any of your routers like so:
app.get('/', function (req, res, next) {
console.log(req.server.get('port')); // displays 3000
});
Function app.listen returns your http server.
Source express/lib/application.js
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
for some reason, for me request.app.server did not work, probably because I was using express 4, after bit of digging up, I found that req.socket.server works.