Node Express: Requests are taking Top-level domain as the subdomain ?? - javascript

I am working on a express project where subdomains are used.
Now the problem i am facing is that my domain name is ("companyName.co.in") and my node JS code is considering companyName as the subdomain.
Here is my code:
server.js
var express = require('express');
var app = express();
var subdomain = require('express-subdomain');
var bodyParser = require('body-parser');
var path = require('path');
var expressValidator = require('express-validator');
var expressJwt = require('express-jwt');
var jwt = require('jsonwebtoken');
var cors = require('cors');
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use(cors());
//app.use(cookieParser());
app.use(express.static('../app'));
app.use(express.static('static/'));
app.use('/api/user',require('./controllers/user.controller'));
var server = app.listen(3000,function(){
console.log('Server listening at 3000');
});
user.controller.js
var express = require('express');
var router = express.Router();
router.get("/details", getUserDetails);
function getUserDetails(req, res) {
var subdomain = (req.subdomains.length > 0) ? req.subdomains[0] : '';
console.log(subdomain)
}
module.exports = router;
So when i call the api/user/details i find that it gives the companyName as the subdomain.
like: requesting from "companyName.co.in"
subdomain should be null but it gives me subdomain as companyName.
Can you please help how can i let the node server know that "companyName.co.in" this is the host and also allow "*.companyName.co.in" where the subdomain can be anything.

You can solve this in your case by setting the 'subdomain offset' express app setting to 3.
http://expressjs.com/en/4x/api.html#app.settings.table
var express = require('express');
var app = express();
app.set('subdomain offset', 3);

Related

Getting a cross origin error. Using react/redux/node/express/mongodb

I had this fixed by adding app.use(cors()) on my index page of my server, but now that I have added a mongodb URI from mlab I seem to be having an issue with it.
I am getting this error: XMLHttpRequest cannot load http://localhost:3000/posts. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Here is my index.js:
require('babel-core/register')({
"presets":["es2015", "react", "stage-1"]
});
const express = require('express');
const http = require('http');
const bodyParser = require('body-parser');
const morgan = require('morgan');
const router = require('./router');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
var favicon = require('serve-favicon');
//DB setup
mongoose.connect('mongodb://****:****#****:****/*****')
mongoose.Promise = global.Promise;
//App setup
const app = express();
app.use(express.static(__dirname + "../client/public"));
// app.use(morgan('combined'));
router(app);
app.use(cors());
app.use(bodyParser.json({type: '*/*'}))
//Server setup
const port = process.env.PORT || 3000;
app.listen(port, function() {
console.log('Server listening on: ', port);
});

Node js express js proxy

Here is an image of the error. I developed an application on AngularJS, and when I run node server by using public wifi my application is running fine. However, when I run it on org network/company wifi my application doesn't work. Any help?
server.js code
var express = require("express");
var open = require("open");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var fs = require("fs");
var path = require("path");
var auth = require("./api/auth");
//var users = require("./api/users");
var transactions = require("./api/transactions");
//var serviceTypes = require("./api/serviceTypes");
var app = express();
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
app.use(cookieParser());
app.use(express.static("boilerplate"));
app.use(express.static("./"));
app.listen(3000, function () {
console.log("server is running on port:3000");
open("http://localhost:3000/");
});
app.get("/", function (req, res) {
res.sendFile(path.join(__dirname, "boilerplate/index.html"));
});
app.use("/auth", auth);
//app.use("/users", users);
app.use("/transactions", transactions);
//app.use("/servicetypes", serviceTypes);

How to set up mongodb with express?

New to Express App , I am trying to setup mongodb using express and node.js. I have some issues if i can get some help in this area. i tried to add directories refrences so you can have idea.
1- var config is coming undefined not sure path is correct.
2- getting SyntaxError: Unexpected reserved word for
require('./config/express')(app);.
Basically trying to have app running with local mongodb.
server > app.js
var express = require('express');
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var config = require('./config/environment');
var http = require('http');
var https = require('https');
var fs = require('fs');
var bodyParser = require('body-parser');
// Connect to MongoDB
mongoose.connect(config.mongo.uri, config.mongo.options);
mongoose.connection.on('error', function(err) {
console.error('MongoDB connection error: ' + err);
process.exit(-1);
});
// Setup server
var app = express();
var server = http.createServer(app);
require('./config/express')(app);
require('./routes')(app);
// Start server
function startServer() {
server.listen(config.port, config.ip, function() {
console.log('Express server listening on %d, in %s mode', config.port, app.get('env'));
});
}
setImmediate(startServer);
// Expose app
exports = module.exports = app;
server > config > express.js
var express = require('express');
var morgan = require('morgan');
var bodyParser = require('body-parser');
var path = require('path');
var config = require('./config/environment');
var session = require('express-session');
var connectMongo = require('connect-mongo');
var mongoose = require('mongoose');
var mongoStore = connectMongo(session);
export default function(app) {
var env = app.get('env');
app.set('views', config.root + '/server/views');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
/*app.use(compression());*/
app.use(bodyParser.urlencoded({
extended: false
}));
app.set('appPath', path.join(config.root, 'client'));
if ('development' === env || 'test' === env) {
app.use(express.static(path.join(config.root, '.tmp')));
app.use(express.static(app.get('appPath')));
app.use(morgan('dev'));
server > config > environment > development.js
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://localhost/test-modeler-dev'
},
// Seed database on startup
seedDB: false
};
As it was pointed out in the comments of the question, your problem is that you are using newer JavaScript features with an older version of Node. To get around the current error, you should change this line in server > config > express.js:
// ...
export default function(app) {
// ...
To
// ...
module.exports = function(app) {
// ...
This should solve this particular problem. But if the code you are using is using other features of ECMAScript 2015 that aren't supported by your version of Node, then you have two options:
Update to the latest version of Node.js here.
Refactor all of your code remove all ECMAScript 2015 features to ensure that it works with your version of Node.js.
Hope this helps.

node js post request.body undefined

server.js
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
router/main.js
module.exports = function(app, fs)
{
app.post('/addUser/', function(req, res){
console.log(req.body);
});
}
I use postman tool!! requets param {"password" : "pass","name" : "dltlsdn"}
but... req.body is undefind.... why..??
Reorder the app.use statement. Earlier you were processing the request before passing through the body-parser.
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var session = require('express-session');
var fs = require('fs');
//body parser before routes
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
var router = require('./router/main')(app, fs);
var server = app.listen(3000, function(){
console.log('Express server has started on port 3000');
});
Hope it helped you.

How to access header information on node js?

How can i read cookie on node js ??
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 8000;
var mysql = require('mysql');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var user_id= cookies.realtimeid;
console.log(user_id);
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
var cookies = parseCookies();
console.log(cookies);
});
I am new on node and socket. I have to read cookie value that is set by codeignter.
How can i send header request on parseCookies from server.listen.
I see you are using express, so I suggest you to use the very well known module for it. cookie-parser https://www.npmjs.com/package/cookie-parser
Installation
npm install cookie-parser
HOW TO USE IT
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
So basically after your mysql require you can do app.use(cookieParser())
And then in every request you do in the req variable you will find the cookies with req.cookies
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)

Categories

Resources