I am trying to prepend a NodeJS request through express to include /api/v1. If I make an addition like to to my server.js file:
app.all('/Employees', require('./routes/Employees'));
I am able to go forward to localhost/Employees and get the proper response (it comes back from the javascript I have written in ./routes/Employees)
If I add /api/v1/ to the beginning of the app.all call, like so:
app.all('/api/*', requireAuthentication);
I am not able to go forward to localhost/api/v1/Employees. The express manual even has an explicit note about this:
Another example is white-listed "global" functionality. The example is much like before, however it only restricts paths that start with "/api":
http://expressjs.com/api.html#app.all
Any help would be greatly appreciated.
Your app gets confused whenever request is received at /api/* -- it doesn't know where to go and what to do now.
If you want to prefix /api/v1 for your requests, you can do it with couple of ways - Choose what best suits your in your case:
Mountpath way -
var express = require('express'),
app = express(),
api = express();
api.all('/employees', function(req, res){
console.log("url :: " + api.mountpath);
res.send('hit at employess');
});
//you can do this here fo v(n)
app.use('/api/v1', api);
app.listen(3000);
other way -
var express = require('express');
var app = express();
app.all('/employees', function(req, res){
res.send('/employe');
});
app.use('/api/v1', function(req, res, next){
res.redirect(req.path);
});
app.listen(3000);
Happy Helping!
Related
I'm trying to use https://github.com/bmullan91/express-subdomain for subdomain routing in express. The following are the contents of my main.js and src/routes/site files.
const express = require('express');
const bodyParser = require('body-parser');
const subdomain = require('express-subdomain');
const siteRouter = require('./src/routes/site');
const app = express()
app.use(express.json() );
app.use(express.urlencoded());
app.use(express.static('public'));
app.use(subdomain('*.www', siteRouter));
app.get('/', function(req, res) {
res.send('Homepage');
});
const server = app.listen(80,'x3.loc', function () {
var host = server.address().address;
var port = server.address().port;
console.log('X3 listening at http://%s:%s', host, port);
});
const express = require('express');
let router = express.Router();
router.get('/', function(req, res) {
res.send('Welcome to site');
});
module.exports = router;
This way of doing app.use(subdomain('*.www', siteRouter)); has been suggested in https://github.com/bmullan91/express-subdomain/issues/33 but does not work.
I have also tried just * as the subdomain aswell, but that caused the homepage w/o a subdomain, to get treated like one aswell. How could I get this to work?
We know that / matches any base path regardless of subdomain. So I made your homepage middleware "subdomain-aware" like so:
app.get('/', function(req, res,next) {
/* If there are any subdomains, skip to next handler, since request is not for the main home page */
if (req.subdomains.length > 0) {
return next();
}
res.send('Homepage');
});
Then I placed the middleware for subdomains below the homepage middleware like so:
app.use(subdomain('*', siteRouter));
This makes homepage middleware to serve requests for x3.loc and the subdomain middleware to serve requests for any subdomain like api.x3.loc or api.v1.x3.loc.
But in my opinion, the real fix should be done in the module. I think it should be changed so that either the case where req.subdomains being empty is handled, or * is matched against an actual string, instead of skipping the iteration.
I am surprised that the fix suggested in bug 33 worked as-is for the reporter. In my testing, it works the opposite way i.e. www.example.com goes to subdomain middleware while stat1.example.com goes to the homepage middleware. Perhaps the reporter saw this and swapped the middleware bodies.
I have been looking for solutions for a couple days now trying to google it and all and now i am here. I am trying to setup subdomains for my app using express-subdomain package. However in the example below the app ALWAYS returns app.get route and skips the other subdomain routes specified.
I have also in turn added the hosts file url so i know that should not be the issue.
It must be in my code for some reason it always ends up displaying Detect Region route even when accessing oce.localhost:3000.
Please help me :)
Server.js
var subdomain = require('express-subdomain');
var express = require('express');
var app = express();
// Region routes
var router = express.Router();
var na = require('./routes/region/na.js');
var oce = require('./routes/region/oce.js');
router.use(subdomain('na.localhost', na));
router.use(subdomain('oce.localhost', oce));
app.get('/', function(req, res) {
res.send('Detect Region and send to correct subdomain!');
});
app.listen(3000);
routes/region/oce.js
var
express = require('express'),
router = express.Router();
router.get('/', function(req, res) {
res.send('Your are in OCE Region!');
});
module.exports = router;
And na.js is pretty much the name as oce.js
Cheers
You are setting your subdomains in the router variable but you don't tell your app to use it.
You have to do that :
app.use(router);
You put it in place of your current app.get.
Edit
You could also put your app.get after the app.use(router) so that it will act as a default route. (When you are neither on oce or na, it will use it)
Edit after some testing
Alright I've been able to make it work using express-vhost. I just updated your server.js like so :
var subdomain = require('express-vhost');
var express = require('express');
var app = express();
// Region routes
var router = express.Router();
var na = require('./routes/region/na.js');
var oce = require('./routes/region/oce.js');
subdomain.register('na.localhost', na)
subdomain.register('oce.localhost', oce)
app.use(subdomain.vhost(app.enabled('trust proxy')));
app.get('/', function(req, res) {
res.send('Detect Region and send to correct subdomain!');
});
app.listen(3000);
I'm probably going to ask a huge noob question, one of the worst I've ever had asked here, but I'm lost as hell with Node/Express. I've only used Apache servers (typical WAMP/XAMP for testing purposes), so I have absolutely no idea on what I have to do to serve my web app.
My folder tree is the following:
www
nodeserver.js
(more things)
Liteconomy (my web app)
js
css
plugins
templates
index.html
sublime_project
Pretty typical, huh? Well, I've been searching how to serve this app with a simple access like localhost:8080/Liteconomy, or localhost:8080/Liteconomy.html. After that, my angular routing would do the rest, but I just can't serve the app.
I've got this written in nodeserver.js:
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!');
});
app.listen(8080, function () {
console.log('Example app listening on port 8080!');
});
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
When I execute it and access to localhost:8080, I get the "Hello world", but when I go to localhost:8080/Liteconomy, I get the following plain text: "Liteconomy/index.html". If I try to access to the index resource directly, I get a "Cannot GET /Liteconomy/index.html" error.
I also tried using the static thingy, but didn't work either.
What am I doing wrong here? I guess I'm just missing something very important.
Do the following, it will resolve your issue.
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
// uncomment following if you want to access your app from /liteconomy
//app.use('/liteconomy', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
//This will enable you to access it form '/'
app.use('/', express.static(__dirname + '/Liteconomy', {index: "index.html"}));
// Rest of the stuff
Then if you will visit your URL that you set and port, you'll be able to access.
Using express.static is recommended way of serving static content.
Hope it helps!
You get a plain text answer because you actually ask to do it with the :
app.get('/Liteconomy', function (req, res) {
res.send('Liteconomy/index.html');
});
If you want to send a simple html file like your index.html file, you should use the "sendfile " function :
app.get('/Liteconomy', function (req, res) {
res.sendfile(__dirname + '/Liteconomy/index.html');
});
"__dirname" represents your root directory path and then you simply put your file path.
Hope that helps !
PS : by default express come with jade and ejs template support instead of just using html. I would advise you to take a look at one of them, it can be a great help to construct your application web pages.
I'm using the body-parser npm package to parse POST data in Application/JSON format and using a few different express routers to modularize the routes I'm creating. Here's the important info in my main server.js file:
server.js
var express = require('express');
var bodyParser = require('body-parser');
app.use(bodyParser.json());
// I'm using a sessionId to identify a person in this dummy app instead of adding in authentication. So the API call is sent to http://localhost:5000/johndoe/todo
app.use('/:sessionId/todo', require('./routes/todoRoutes'));
var port = process.env.PORT || 9191;
app.listen(port, function () {
console.log('Express server listening on port ' + port);
});
todoRoutes.js:
var todoRouter = require('express').Router();
todoRouter.post('/', function (req, res) {
console.log("This is the post data:");
console.log(req.body);
});
module.exports = todoRouter;
req.body seems to be getting lost through the middleware; it logs {} to the console. However, on a whim I added the following to my bodyParsing middleware in server.js:
app.use(bodyParser.json(), function (req, res, next) {
next();
});
And now it's passing req.body through to todoRoutes.js. (It now logs {title: 'Testing'}, etc. to the console like I need it to.)
What's going on here? And what's the best way to structure this so that it works the way it's supposed to? I'm new to Express, so I admit I could be structuring this all wrong.
Ugh, nevermind. I was an idiot and found that the Content-Type Header of application/JSON got turned off in Postman (read: I must have turned it off at some point) and so the bodyParser was never being used.
Dammit.
Thanks for the help to those who responded!
I need to make routing flexible for slashes, for example
app.get('/home/pages')
router must handle
////home///pages
/home/pages////
etc...
requests.
Currently I have one idea to implement this, but for that I need to know how to reroute request via middleware,
If you can answer this question or suggest something else I will be grateful to you.
Also please don't suggest using regex for defining routers, because project is already done and there is a lot of already defined routes.
You need to rewrite url in a middleware:
var express = require('express');
var app = express();
app.use(function (req, res, next) {
req.url = req.url.replace(/\/+/g, '/');
next();
});
app.get('/home/pages', function (req, res) {
res.send('some pages');
});
app.listen(3000);