Return HTML file using Adonisjs Router - html

I am creating one web application using AdonisJs in backend and ReactJs in frontend.
While integrating both frameworks i am struggling to return index.html file of ReactJs on '/' route path from AdonisJs, since AdonisJs is supporting edge.js for view.
Is there any solution in AdonisJs similar to expressjs returning HTML file as given below
const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
app.listen(9000);
Currently my AdonisJs route returning edge file like,
Route.any('*', ({view}) => view.render('index'))

You can change template file extensions in config file which resides on config/app.js.
{
static: {
extensions: ['html']
}
}

For this you need to be running Adonis by motorcycle stack, if using only as API it will only return JSON rendered responses
now if you are in an Adonis stack installation just use the view object that looks like this:
Route.get('/page', ({ view }) => {
view.render('name_of_view')
})

Related

Showing HTML file in Node js Application

I am new on Node.js and I have app.js file like:
const express = require('express');
const app = express();
const port = 8080;
app.get('/', (req, res) => res.send('Hello World'));
app.listen(port);
console.log(`App running on http://localhost:${port}`);
I also have index.html file in the same folder with app.js. Here there is a HTML5 website.
When I run the project I can see Hello World text in browser, How can I show this HTML file from my app.js so when I deploy it, it should show me responsive HTML file instead of Hello World?
I tried
app.get('/',function(req,res) {
res.sendFile('index.html');
});
But didn't see a difference.
To make your code example work you'll need to specify an absolute path, try using this:
res.sendFile(__dirname + "/index.html");
Another way would be to use EJS (https://ejs.co/)
In your example, you could do the following:
Install EJS:
npm install ejs
Set the View Engine to EJS:
app.set('view engine', 'ejs')
- Move your index.html file to a folder called "views" and also rename the file to index.ejs
views/index.ejs
In your app.get() handler, use:
res.render('index')
Final Result:
const express = require("express");
const app = express();
app.set("view engine", "ejs");
const port = 8080;
app.get("/", (req, res) => {
res.render("index");
});
app.listen(port, () => {
console.log(`App running on http://localhost:${port}`);
});
(note: I also moved your console.log to inside app.listen)
I found this on another stack overflow question, it should work
fs.readFile(__dirname + '/views/test.html', 'utf8', function(err, text){
res.send(text);
});

How do 'no code' websites publish webpages for each user? [duplicate]

I am used to working on httpd ( Apache ) which provides a way to configure subdomains which is mapped to a directory.
How can I do the same thing in Connect.js/Express.js ? I see that the only thing that I have is routes which I am not sure how I can use to configure sub domains. I have subdomains like m.mysite.com, sync.mysite.com
Can someone help ?
Or alternatively you could use vhost.
Then, create several sites in their own directory and export the express app, eg. /path/to/m/index.js:
var app = express()
/* whatever configuration code */
exports.app = app
// There is no need for .listen()
And then handle all requests with the following app:
var vhost = require('vhost');
express()
.use(vhost('m.mysite.com', require('/path/to/m').app))
.use(vhost('sync.mysite.com', require('/path/to/sync').app))
.listen(80)
Note that /path/to/m and /path/to/sync can be absolute paths (as written above) or relative paths.
You could append a subdomain to a request and then check for it in subsequent next() calls.
I got the following code from > http://groups.google.com/group/express-js/browse_thread/thread/b04bbaea7f0e8eed (so full credit to the original author)
app.get('*', function(req, res, next){
if(req.headers.host == 'some.sub.domain.com') //if it's a sub-domain
req.url = '/mysubdomain' + req.url; //append some text yourself
next();
});
// This will mean that all get requests that come from the subdomain will get
// /subdomain appended to them, so then you can have routes like this
app.get('/blogposts', function(){
// for non-subdomain
});
app.get('/mysubdomain/blogposts', function(){
// for subdomain
});
I have recently came across this problem, and wrote a module to help with it using express 4. https://www.npmjs.org/package/express-subdomain.
Example - api subdomain.
var express = require('express');
var app = express();
var router = express.Router();
//api specific routes
router.get('/', function(req, res) {
res.send('Welcome to our API!');
});
router.get('/users', function(req, res) {
res.json([
{ name: "Brian" }
]);
});
app.use(subdomain('api', router));
app.listen(3000);
Check out the module on npm to see more examples.
I created a module to help with subdomains in Express: https://github.com/WilsonPage/express-subdomain-handler
Do as I say, create two express app in different folder.
For example:
one app in /blogsite directory
const express = require("express");
const blog = express();
blog.get("/", (req, res) => {
res.send("BLOG SECTION");
});
blog.get("/allblogs", (req, res) => {
res.json([
{ title: "csgo major boston", description: "Best CSGO major ever" },
{ title: "Blast pro series", description: "Coolest series of CSGO" },
]);
});
module.exports = { blog };
and another one in /portfolio directory
const express = require("express");
const portfolio = express();
portfolio.get("/", (req, res) => {
res.send("PORTFOLIO SECTION");
});
portfolio.get("/resume", (req, res) => {
res.send("HERE'S MY RESUME");
});
module.exports = { portfolio };
Now create a main app in the outer folder and import the other two express apps that you just made in /blogsite directory and /portfolio directory.
And in the main app do this,
const express = require("express");
const vhost = require("vhost");
const { blog } = require("./blogsite");
const { portfolio } = require("./portfolio");
const app = express();
// BLOG AND PORTFOLIO
// url: http://blog.localhost:3002/
// url: http://blog.localhost:3002/allblogs
// url: http://portfolio.localhost:3002/
// url: http://portfolio.localhost:3002/resume
app
.use(vhost("portfolio.localhost", portfolio))
.use(vhost("blog.localhost", blog));
// MAIN APP ROUTES OR ENDPOINTS
// url: http://localhost:3002
// url: http://localhost:3002/myhobbies
app.get("/", (req, res) => {
res.send("MAIN APP SECTION");
});
app.get("/myhobbies", (req, res) => {
res.send("MAIN APP -> myhobbies section");
});
app.listen(3002, () => {
console.log("started listening");
});
fileStructure at the end should be looking like this
main(folder)
index.js (main express app which you need to run using node or nodemon)
blogsite(folder that I talked about for blog.localhost)
index.js (blog express app)
portfolio(folder)
index.js (portfolio express app)
I've had this exact same requirement for a project I was working on and ended up throwing together a middleware-based solution. It allows you to define routers and view folders per subdomains.
Check it out on NPM https://www.npmjs.com/package/express-multiview
or GitHub https://github.com/daryl-cecile/express-multi-view#readme

GET to CSS returns 404

So I recently moved my website from a single-page website to an express server. Now I changed the file paths, but I cannot get my css and js files to load.
As seen in the developer console, the GET request to https://<website>.com/public/css/main.css returns a 404.
This is the css link:
<link rel="stylesheet" type="text/css" href="../public/css/main.css">
This is my server:
const express = require('express');
const app = express();
const getpages = require('./router/getpages.js');
app.use('/', getpages);
app.use(express.static('public'));
// 404's
app.use((req, res) => {
res.status(404).send('Page not found or non-existant.<br><br>Home');
});
app.listen(3000, console.log('Running on port 3000'));
This is ./router/getpages.js:
const router = require('express').Router();
const path = require('path');
router.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../views/', 'index.html'));
})
module.exports = router;
This is the file structure:
Note, I could not find any other questions that helped me, before this is marked as a dupe again.
As can be seen from the documentation, you should not have public in the route
https://<website>.com/css/main.css should work as expected.
refer : https://expressjs.com/en/starter/static-files.html
For example, use the following code to serve images, CSS files, and
JavaScript files in a directory named public:
app.use(express.static('public'))
Now, you can load the files that are
in the public directory:
eg : http://localhost:3000/images/kitten.jpg
Express looks up the files relative to the static directory, so the
name of the static directory is not part of the URL.

Next.js stylesheet is not loaded

I'm using Next.js to build my website. I modify the server using express.js server so I have server.js on my root folder of my project.
When I started the server npm run dev which run node server.js, my home page renders correctly. But when I navigate to some of other page in my website, the css is not loaded. But if I refresh the page, it will load the css and the problem is gone
const express = require('express')
const next = require('next')
const dev = process.env.NODE_ENV !== 'production'
const app = next({dev})
const handle = app.getRequestHandler()
app.prepare().then(() => {
const server = express()
server.get('*', (req, res) => {
return handle(req, res)
})
const port = process.env.PORT || 3000
server.listen(port, err => {
if (err) throw err
console.log(`> Ready on port ${port}...`)
})
})
Here's my server.js file. I think there is no problem with the code.
I use #zeit/next-less package for compiling my LESS stylesheet
Please help
Thanks
Check this out: https://github.com/zeit/next-plugins/issues/282
In short as a workaround:
Create an empty CSS file in /static/ directory.
Import it in _app.js:
import '../static/jank-empty.css';
I hope that it would help.
For me the issue was that the nextjs wasn't loading the rel=stylesheet link tags. It was only able to load rel=preload link tags.
so I did a workaround like this:
document.querySelectorAll("link[rel='preload'][as='style']").forEach(link => link.rel = "stylesheet")

Setting up Node.js with express.js on my 'portfolio' site

I'm completely new to node.js but i'm trying to implement it on my personal site so that I start learning it. I have the node server running but i'm trying to set up the routing using express.js . All my files are typical static files .html, .js, .cs, .png , etc. Currently, the route gives me my index page on the 'home' page which is goo. If I attempt to navigate to the index of another diectory, I just get the 404 error page. My file structure is like this:
Server.js
package.json
node_modules
-- views (Folder)
-index.html (File in views)
--Projects (Folder in Views)
-index.html (File in Projects)
my Server.js looks like
var express = require("express");
var app = express();
var router = express.Router();
var path = __dirname + '/views/';
router.use(function (req, res, next) {
console.log("/" + req.method);
next();
});
router.get("/", function (req, res) {
res.sendFile(path + "index.html");
});
router.get("/Projects", function (req, res) {
res.sendFile(path + "Projects/index.html");
});
app.use("/", router);
/*app.use("*", function (req, res) {
res.sendFile(path + "404.html");
});*/
app.listen(3000, function () {
console.log("Live at Port 3000");
});
I've looked for the past ~18 hours at various resources and i'm just missing something i'm sure. My current idea of the issue is the navigation links in the html, however I've attempted changing those with no progress.
If you have only public file (like html, css, ..) you can put everything on a /public folder and add this instead of a router.
app.use(express.static('public'))
Doc: https://expressjs.com/en/starter/static-files.html
Every file will be accessible:
/public/my-folder/my-file.png > www.my-dmain.com/my-folder/my-file.png