In my NODEjs ( using Express ) application, I want to use Country Code inside routes.js but I am unable to access localstorage inside the routes.js
Please provide some solution.
LocalStorage is only available in browsers on the Window object.
The Window object is not available server side.
MDN
Following your comment, you could implement a route in your express application which takes the IP as part of the body.
For this to work you will need body-parser middleware. Example application:
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var server;
app.use(bodyParser.json());
app.get('/api/ip', function (req, res) {
res.send(req.body.ip);
});
server = app.listen(3000);
This would return the posted IP.
Related
We first developed REST api's using node.js and have that running on a VPS. We now have developed an Angular web app to display data that comes in via a mobile app that calls some of the REST api's and then updates the data by calls back to other REST API's. Running the Angular app on the localhost was able to successfully call the REST api's.
We want to combine both applications on the same server. After searching around it seemed that we could add commands to the REST api server.js to pass urls that didn't meet the REST api path to Angular. Code snippet is below:
// API verison
var apiVersion = '/v1'
var fs ;
var https ;
// Dependencies
var express = require('express');
var mongoose = require('mongoose');
var bodyParser = require('body-parser');
// MongoDB
...
// Express
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
fs = require('fs')
https = require('https')
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
// Pass request to angular?
app.use(function(req, res) {
var path = require('path');
res.sendfile(path.resolve('/home/.../index.html')); // but not getting anything
});
The REST api's still work but when directing a browser to 'mydomain.net' I just get a blank page. I don't see any errors on the node/error logs.
Any ideas?
You can do something like this. Use static content to send from the dist folder and rest will work fine. I have added two reference in case you might need them to refer.
var apiVersion = '/v1'
const fs = require('fs')
const https = require('https');
const path = require('path')
// Dependencies
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
// MongoDB
...
// Express
const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Pass request to angular?
app.use('path', express.static(path.resolve('your path should be correct')));
// Routes
app.use(apiVersion, require('./routes/api'));
// Start server
https.createServer({
key: fs.readFileSync('...'),
cert: fs.readFileSync('...')
}, app)
.listen(443, function () {
console.log('HTTPS Server running on default port 443')
});
Check here1 or here2 for more details, there are simple steps to follow.
As mentioned in express routing guide and this answer, we can create "mini-app" and use it from the main app. However I saw a code where it uses app instead of router in the module
app.js
var express = require('express');
var userRoutes = require('./routes/user');
var app = express();
app.use('/user', userRoutes);
module.exports = app;
routes/user.js
var express = require('express');
var app = express(); // not express.Router() !!
app.get('/:name', function(req, res) {
var userName = req.params.name;
res.render('user.jade', {
userName: userName
});
});
module.exports = app;
I assumed the correct usage in routes/user.js should be
router = express.Router()
instead of
app = express()
but app = express() also works! what are the differences and why router = express.Router() is better?
When you are working with a server where there are many routes, it can be confusing to leave them in a Main file together. The let router = express.Router() option works differently than let app = express().
While the app returns an app object, router will return a small app fragment, similar to the app, where you will use logic to call them later on the Main.
The most important, about your question, is that a router, which is isolated, will not interfere with others in the application, being a single environment.
https://expressjs.com/en/api.html#router
A router object is an isolated instance of middleware and routes. You can think of it as a “mini-application,” capable only of performing middleware and routing functions. Every Express application has a built-in app router.
A router behaves like middleware itself, so you can use it as an argument to app.use() or as the argument to another router’s use() method.
I'm very new to express and am running into issues getting proper routing set up. It's a homework assignment so the router file was already written, but there's a express.js file we're supposed to fill in to make calls to the api whenever a get/put/post/delete request is made at that address. The router file is set up like this:
var listings = require('../controllers/listings.server.controller.js'),
getCoordinates = require('../controllers/coordinates.server.controller.js'),
express = require('express'),
router = express.Router();
/*
These method calls are responsible for routing requests to the correct request handler.
Take note that it is possible for different controller functions to handle requests to the same route.
*/
router.route('/')
.get(listings.list)
.post(getCoordinates, listings.create);
/*
The ':' specifies a URL parameter.
*/
router.route('/:listingsId')
.get(listings.read)
.put(getCoordinates, listings.update)
.delete(listings.delete);
/*
The 'router.param' method allows us to specify middleware we would like to use to handle
requests with a parameter.
Say we make an example request to '/listings/566372f4d11de3498e2941c9'
The request handler will first find the specific listing using this 'listingsById'
middleware function by doing a lookup to ID '566372f4d11de3498e2941c9' in the Mongo database,
and bind this listing to the request object.
It will then pass control to the routing function specified above, where it will either
get, update, or delete that specific listing (depending on the HTTP verb specified)
*/
router.param('listingId', listings.listingByID);
module.exports = router;
And the express.js file is like this:
var path = require('path'),
express = require('express'),
mongoose = require('mongoose'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
config = require('./config'),
listingsRouter = require('../routes/listings.server.routes'),
getCoordinates = require('../controllers/coordinates.server.controller.js');
module.exports.init = function() {
//connect to database
mongoose.connect(config.db.uri, {useMongoClient: true});
//initialize app
var app = express();
//enable request logging for development debugging
app.use(morgan('dev'));
//body parsing middleware
app.use(bodyParser.json());
/* server wrapper around Google Maps API to get latitude + longitude coordinates from address */
app.post('/api/coordinates', getCoordinates, function(req, res) {
res.send(req.results);
});
This is the part I can't figure out:
/* serve static files */
app.get('/listings', listingsRouter, function(req, res){
res.send(req.get('/'))
});
/* use the listings router for requests to the api */
/* go to homepage for all routes not specified */
return app;
};
I'm just not sure how to use the routes in the listingsRouter file with the req and res objects and I can't find any examples of a program set up like this to help. Any assistance would be appreciated.
Change following
app.get('/listings', listingsRouter, function(req, res){
res.send(req.get('/'))
});
To
app.use('/listings', listingsRouter);
Express Router. Scroll down to express.Router section for complete info.
Hope this helpls.
I have an Express.js application running on https://mydomain.tld/folder. It sets up the route middlewares with
app.use('/path', middleware)
but only the one for the '/' path is working properly. I'm guessing this is because Express is looking for requests on https://mydomain.tld/path instead of on https://mydomain.tld/folder/path.
How can I get Express to process the requests for https://mydomain.tld/folder/path (preferably without having to hard code the path)?
Using a router:
// myRouter.js
var express = require('express')
var router = express.Router()
router.get('/path', middleware)
// other routes...
module.exports = router
Now you can use your router with the relative path you want:
var myRouter = require('./myRouter')
app.use('/folder', myRouter)
From koajs.com:
app.callback()
Return a callback function suitable for the http.createServer() method to handle a request. You may also use this callback function to mount your koa app in a Connect/Express app.
Now I have an Express app that already starts its own http server. How can I mount a koa app on top of this existing server, so that it shares the same port?
Would I include the koa app as an Express middlware? Do I still use app.callback() for that?
expressapp.use(koaapp.callback()) is fine. but remember, koaapp.callback() does not have a next, so there's no passing errors to the express app or skipping the koaapp once you use it.
it's better to keep them completely separate since their APIs are incompatible
var koaapp = koa()
var expressapp = express()
http.createServer(req, res) {
if (true) koaapp(req, res);
else expressapp(req, res);
})
Since you need a server instance in order to mount a middleware on a specific /prefix, it would be something like
var http = require('http');
var expressApp = require('express');
var koaApp = require('koa');
// ...
expressApp.use('/prefix', http.createServer(koaApp.callback()));