Hi friends I am working with node.js and express. I have some endpoints and inside there are dynamic files every file have a name of an IP for example services/192.168.0.1.html, service/192.168.0.11.html, service/192.168.0.15 etc. So I want to make a dynamic route like this code:
app.get('/endpointej/**REGEXP**forIP.html', (req, res) => {
var ruta = {
root: path.join(__dirname + 'endpoint/)
}
res.sendFile("IPfiledinamic.html",ruta)
});
Can some one help me out please ?
Regards
You can use something like
// route is for GET /test/1.1.1.1.html, but not for GET /test/1.2.3.html
app.get(/test\/([0-9]{1,3}\.){3}[0-9]{1,3}\.html/, (req, res) => {
const ipRegex = /^\/test\/((?:[0-9]{1,3}\.){3}[0-9]{1,3})\.html$/
// do more here...
res.status(200).send(`matches, ${req.url.match(ipRegex)}`)
})
Related
router.get("/(A|B)/account/", async (req, res) => {});
How to do I reference the (A|B) inside of the async function?
I guess your route responsibility is getting account information of only A or B. So let's change your router path to /account/:name(A|B), then your express router will look like this:
router.get("/account/:name(A|B)", async (req, res) => {
const name = req.params; // A or B
});
Only 2 kinds of requests are handled by this router:
GET /account/A
or
GET /account/B
I am trying to learn how to create a facebook Bot.
I found this amazing article on Medium which illustrates how we can create a messenger bot
In this article, The author tells us to create a verification.js. file inside controllers/verification.js. and paste the following code in it.
module.exports = (req, res) => {
const hubChallenge = req.query[‘hub.challenge’];
const hubMode = req.query[‘hub.mode’];
const verifyTokenMatches = (req.query[‘hub.verify_token’] === ‘crowdbotics’);
if (hubMode && verifyTokenMatches) {
res.status(200).send(hubChallenge);
} else {
res.status(403).end();
}
};
This, I understand to be ES6 Anonymous function which executes immediately? And since we aren't doing anything like
var express = require("express");
var app = express();
I am assuming it to be simple Vanilla JavaScript file. Now in our app.js we just import like this const verificationController = require("./controllers/verficiation.js")
Now, The question which is bothering me is that how did we passed the arguments to this module.exports = (req, res) => {
Without reading the article or knowing anything about that bot, I assume you are going to use verificationController as middleware to an express route, like this:
app.get("/", verificationController, (req, res) => {...});
This will pass req and res as parameters to the function
I want to use routes something like this.
For example :
routes.use((req, res, next) => {
/**
* I have an example routes from database and i was passing into variable
* I'm assign fromDb as 'api/test'
*/
var a = fromDb;
next()
})
routes.get(a, (req, res, next) => {
console.log(req.path)
})
I know, a variable in next routes do not get a value from DB cause functional scope. So, any idea for solve this method. I just wondering if I can using modular like this
const DBRoutes = require('lib/example.js')
router.get(DBRoutes, (req, res) => {
console.log(req.path)
})
Any idea for the best method? Thanks
You want to add a route based on content in your database
So you could do the lookup and on success create the route
eg:
dbConnection.lookup(...some query)
.then((pathFromDB) => {
// where pathfromDb = /api/test
routes.get(pathFromDB, (req, res, next) => {
console.log(req.path)
})
});
routes.use((req, res, next) => {
/**
* I have an example routes from database and i was passing into variable
* I'm assign fromDb as 'api/test'
*/
res.locals.fromDb = fromDb;
next()
})
routes.get('/your/route', (req, res, next) => {
console.log(req.path);
console.log(res.locals.fromDb);
});
This is one way of passing variables through different middlewares in express.
I don't think you can dynamically set up routes for express web server. However, routes are set up once during startup. You can get the routes from database at that time.
const route = await routeFromDatabase();
routes.get(route, (req, res, next) => {
console.log(req.path);
console.log(res.locals.fromDb);
});
If you change the database after startup, you will have to restart the node app.
Update 19th Feb 2018: User mentioned the use case as API Gateway. This is worth exploring for such use cases: https://www.express-gateway.io/
I have an ExpressJS routing for my API and I want to call it from within NodeJS
var api = require('./routes/api')
app.use('/api', api);
and inside my ./routes/api.js file
var express = require('express');
var router = express.Router();
router.use('/update', require('./update'));
module.exports = router;
so if I want to call /api/update/something/:withParam from my front end its all find, but I need to call this from within another aspect of my NodeJS script without having to redefine the whole function again in 2nd location
I have tried using the HTTP module from inside but I just get a "ECONNREFUSED" error
http.get('/api/update/something/:withParam', function(res) {
console.log("Got response: " + res.statusCode);
res.resume();
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
I understand the idea behind Express is to create routes, but how do I internally call them
The 'usual' or 'correct' way to handle this would be to have the function you want to call broken out by itself, detached from any route definitions. Perhaps in its own module, but not necessarily. Then just call it wherever you need it. Like so:
function updateSomething(thing) {
return myDb.save(thing);
}
// elsewhere:
router.put('/api/update/something/:withParam', function(req, res) {
updateSomething(req.params.withParam)
.then(function() { res.send(200, 'ok'); });
});
// another place:
function someOtherFunction() {
// other code...
updateSomething(...);
// ..
}
This is an easy way to do an internal redirect in Express 4:
The function that magic can do is: app._router.handle()
Testing: We make a request to home "/" and redirect it to otherPath "/other/path"
var app = express()
function otherPath(req, res, next) {
return res.send('ok')
}
function home(req, res, next) {
req.url = '/other/path'
/* Uncomment the next line if you want to change the method */
// req.method = 'POST'
return app._router.handle(req, res, next)
}
app.get('/other/path', otherPath)
app.get('/', home)
I've made a dedicated middleware for this : uest.
Available within req it allows you to req.uest another route (from a given route).
It forwards original cookies to subsequent requests, and keeps req.session in sync across requests, for ex:
app.post('/login', async (req, res, next) => {
const {username, password} = req.body
const {body: session} = await req.uest({
method: 'POST',
url: '/api/sessions',
body: {username, password}
}).catch(next)
console.log(`Welcome back ${session.user.firstname}!`
res.redirect('/profile')
})
It supports Promise, await and error-first callback.
See the README for more details
Separate your app and server files with the app being imported into the server file.
In the place you want to call your app internally, you can import you app as well as 'request' from 'supertest'. Then you can write
request(app).post('/someroute').send({
id: 'ecf8d501-5abe-46a9-984e-e081ac925def',
etc....
});`
This is another way.
const app = require('express')()
const axios = require('axios')
const log = console.log
const PORT = 3000
const URL = 'http://localhost:' + PORT
const apiPath = (path) => URL + path
app.get('/a', (req, res) => {
res.json('yoy')
})
app.get('/b', async (req, res) => {
let a = await axios.get(apiPath('/a'))
res.json(a.data)
})
app.listen(PORT)
I'm following this tutorial (source code) and added the highlighted code.
// app.js
app.get("/notebooks", function(req, res) {
var client = new Evernote.Client({ token: req.session.oauthAccessToken }),
noteStore = client.getNoteStore();
noteStore.listNotebooks(function(err, noteBooks) {
res.send(err || noteBooks);
});
});
app.get('/importNotes', function (req, res) {
res.send('importNotes');
});
app.get("/notes/:guid", function(req, res) {
var client = new Evernote.Client({ token: req.session.oauthAccessToken }),
noteStore = client.getNoteStore();
noteStore.getNote(req.params.guid, true, true, true, true, function(err, note) {
if (!err) {
note.content = ENML.HTMLOfENML(note.content, note.resources);
}
res.send(err || note);
});
});
another attempt:
app.get('/importNotes', function (req, res) {
res.render('importNotes', {});
});
I created importNotes.html near to index.html.
After starting the server with node app.js
I'm getting an error stating Cannot GET /importNotes
when I access localhost:3000/importNotes
I plan to use this page to add additional features after I deal with this issue (import the notes from the special txt file).
What I'm doing wrong and how I can correct it?
How to define correctly the needed routes ?
This is Steve - thanks for trying out the code !
If you use this code :
app.get('/importNotes', function (req, res) {
res.send('importNotes');
});
Then I would expect the server will send back to the browser the string "importNotes". Perhaps if you have a file called "importNotes" there is some confusion.
If you want to create a file called importNotes.html - then just put it into the "public" folder. It will then be accessible via localhost:3000/importNotes.html
The line :
app.use(express.static(__dirname + "/public"));
Tells Express to serve the contents of the "public" folder at the root level of your application, so any files you put in that folder should be GETable. e.g.
/public
index.html
steve.html
localhost:3000/steve.html