let express.js redirect all sub-path of any html file path to itself - express

I have this code on file server.js:
const express = require('express');
const { join } = require('path');
const app = express();
app
.get(':path.html/*', (req, rep) => {
rep.sendFile(join(__dirname, req.params.path+'.html'));
})
.listen(8080)
I run it (node server.js) then when I visit
http://localhost:8080/foo.html/aaa or
http://localhost:8080/foo.html/bbb/ccc
I get the content of foo.html.
This works for any html file of ./*.html
I would like this works for any html file of ./**/*.html
For example when I visit http://localhost:8080/sub/dir/bar.html/foo I want to get content of sub/dir/bar.html
how to do that with express router syntax?

Related

express cant be shown in localhost

I am a beginner to express,but in have diffculities when linking with the localhost in my internet.But it works fine a minute ago, it shows no error and with fine console log,but the website just stuck on the url without any error.I am wondering is the bug occur on my script or my internet
my code:
const bodyParser = require('body-parser')
const express = require('express')
const app = express()
console.log("ff")
const mongoose=require('mongoose')
mongoose.set('strictQuery',false)
require('dotenv/config')
const db=mongoose.connection
db.on('error',(error)=>console.error(error))
db.once('open',()=> console.log('connect to db'))
mongoose.connect(
process.env.DB_CONNECTION
,{ useNewUrlParser:true })
app.use(logger)
app.use(bodyParser.json)
app.get('/',logger,(req,res)=>{
console.log("ddd")
//res.status(500)
res.json({ username : "alex"})
})
const userRouter = require('./routes/users')
function logger(req,res,next){
console.log(req.originalUrl)
next()
}
app.use('/users',userRouter)
app.listen(3000)
I think the bodyParser is the problem.
I changed it and now your code works for me
use this:
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json()); //<- () missing

How can I configure my Nuxt (version 2.13.2) app to use Express?

I have set up several Nuxt applications using ExpressJS on Nuxt version 2.12.x, but the option is no longer present in the configuration setup with npx create-nuxt-app.
Previously, create-nuxt-app created a file server/index.js like this:
const express = require('express')
const consola = require('consola')
const { Nuxt, Builder } = require('nuxt')
const app = express()
// Import and Set Nuxt.js options
const config = require('../nuxt.config.js')
config.dev = process.env.NODE_ENV !== 'production'
async function start() {
// Init Nuxt.js
const nuxt = new Nuxt(config)
const { host, port } = nuxt.options.server
await nuxt.ready()
// Build only in dev mode
if (config.dev) {
const builder = new Builder(nuxt)
await builder.build()
}
// Give nuxt middleware to express
app.use(nuxt.render)
// Listen the server
app.listen(port, host)
consola.ready({
message: `Server listening on http://${host}:${port}`,
badge: true
})
}
start()
However, using create-nuxt-app with Nuxt version 2.13.2 no longer creates this server/index.js file. I have tried creating a server/index.js file and also server.js and neither change the default behavior of the nuxt command.
How can I configure my nuxt app to use Express other than downgrading to 2.12?
Please go through this below link:
https://nuxtjs.org/api/configuration-servermiddleware/
You just need to define the parameter named serverMiddleware in the nuxt.config.js file, and the value of this parameter is the path to your server/index.js file.

How to pass this module's data into index.ejs with Express?

Stuck on my first very basic app. The 'heavy lifting' works: the scrape.scrape(); function imports a module, which returns an array of strings (by scraping an external site).
When I run 'node index.js', I see the array being returned in terminal, and when I open localhost:3000 it just 'hello world'. But if I open devtools on this localhost index page, there's nothing being logged in console.
index.js
var scrape = require('./src/scraper');
var express = require('express');
var app = express();
scrape.scrape();
// returns ['headline one','headline two', etc...]. Trying to pass this data to index.ejs
app.set('port', process.env.PORT || 3000);
app.get('/', function(req, res) {
res.render('index.ejs');
});
/views/index.ejs
<body>hello world</body>
your controller here index.js
var array = scrape.scrape(); //pass this array in res.render
app.set('port', process.env.PORT || 3000);
app.get('/', function(req, res) {
res.render('index.ejs', {data : array});//your data is render through view
});
your ui here index.ejs
<body>hello world</body>
<h1><%= data[0] %></h1> //your data will render here
official ejs documentation here
hope this helps you

how can I use express code to map a route in a sails hook?

In express code:
var kue = require('kue');
var express = require('express');
var ui = require('kue-ui');
var app = express();
app.use('/api', kue.app);
app.use('/kue', ui.app);
I can access: http://localhost:1337/kue and http://localhost:1337/api just fine.
I tried to move this into my sails hook:
var kue = require('kue');
var ui = require('ui');
module.exports = function galaxyKueSyncHook(sails) {
return {
routes: {
before: {
'get /kue': ui.app,
'get /api': kue.app
}
}
};
}
It doesn't work. I get a blank pages when access the same URLs.
How do properly get this to work in sails?
Additionally, I was able to get express code to work in config/http.js with
module.exports.http = {
customMiddleware: function (app) {
app.use(...);
But, I really want the function to be added in an installable hook.
You can use express like:
var app = sails.hooks.http.app;
app.use('/api', kue.app);

cannot get app.local to a routing file

So, in my express.js 4.13.3. , in the app.js file I set an app.local var
app.set('multimedia', __dirname + '/public/multimedia');
then in the routes/settings.js I try to access that var like
var app = require('../app');
var dir = app.get('multimedia');
and I get app.get is not a function.
I also tried var dir = app.get.multimedia; and var dir = app.locals('multimedia'); and var dir = app.locals.multimedia; and still nothing.
What am I missing here?
Thanks
The problem is that you have not defined what to do when required('../app') is called. You should do this using module.exports as shown below. Try one of these approaches to fix this problem.
Approach 1:
Add this line to the app.js file.
module.exports = app;
This simply says to export the app whenever require('../app') is called. If you use require('routes/settings'); within the app.js, this line should be placed before the require('routes/settings'); or it will not work.
Approach 2:
//change the `routes/settings.js` like this
module.exports = function (app) {//notice that you pass the app to this
//............
var dir = app.get('multimedia');
console.log(dir);
//............
}
Add this line to app.js
require('routes/settings')(app);
Now you should be able to use the app.get() without any problem.
Example:
//app.js
var express=require('express');
var app = express();
app.set('multimedia', __dirname + '/public/multimedia');
app.get('/',function(req,res){
res.send('Hello World!');
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Listening at http://%s:%s', host, port);
});
module.exports=app;
require('./settings');
//settings.js
var app= require('./app');
var dir = app.get('multimedia');
console.log(dir);
More details about module.exports can be found here
In settings.js
function settings(app) {
console.log(app);
// etc...
}
module.exports = settings;
In app.js:
var settings = require('./settings'),
express = require('express'),
app = express(),
server = require('http').createServer(app),
...
...
settings(app);
Basically you export the function from where you want to use them and then require those files in app.js.
Sample project:
server.js:
var settings= require('./settings'),
server = require('http');
settings(server);
settings.js:
function settings(server) {
console.log("Hello");
console.log(server);
}
module.exports = settings;
Both files are in the same folder.
To run: node server
Result: