I'm using deno, oak, and view_engine.
Here is my file structure:
server.ts
routes
user.ts
view
index.ejs
/user
index.ejs
On my server.js this code works as expected:
router
.get("/", (context: any) => {
context.render("view/index.ejs");
});
But, in my routes/user.ts, the following code does NOT work:
router
.get("user/", (ctx: any) => {
ctx.render("../view/user/index.ejs")
});
Inside render, I tried:
${Deno.cwd}"/../view/student/index.ejs"
"/../view/user/index.ejs"
and out of desperation:
"/view/user/index.ejs"
I'm sure there's a super easy, most obvious thing I'm missing here.
Here is workaround,
import { Application, send, Router } from "https://deno.land/x/oak/mod.ts";
import { viewEngine, engineFactory, adapterFactory, ViewConfig } from 'https://deno.land/x/view_engine/mod.ts';
const ejsEngine = engineFactory.getEjsEngine();
const oakAdapter = adapterFactory.getOakAdapter();
const app = new Application();
app.use(viewEngine(oakAdapter, ejsEngine, {
viewRoot: "./view",
viewExt: ".ejs",
}));
const router = new Router();
app.use(router.routes());
app.use(router.allowedMethods());
router
.get('/', async (ctx, next) => {
ctx.render("index", { data: { name: "Nikhil" } });
});
await app.listen({ port: 8000 });
Inside the view folder i have index.ejs
Run files as,
deno run --allow-net --allow-read server.ts
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>EJS HOLA</h1>
Hobbies of <%=data.name%>
</body>
</html>
For more resource to add, you can look at view_engine
Related
I have created a site, that have root, help and 404 paths and pages in hbs format. The issue is that when I run localhost:3000/wrong it shows the site correctly but when I run localhost:3000/help/wrong the css part doesn't get applied to that 404 page as it should, because there is not route /help/wrong.
I run the code using node app.js or nodemon app.js.
Folder Structure:
public
css
styles.css
templates
partials
animal.hbs
info.hbs
views
404.hbs
help.hbs
index.hbs
app.js
package.json
package-lock.json
package.json
"dependencies": {
"express": "^4.17.1",
"hbs": "^4.1.1"
},
"devDependencies": {
"nodemon": "^2.0.7"
}
app.js
const express = require("express");
const hbs = require("hbs");
const app = express();
app.set('view engine', 'hbs');
app.set('views', './templates/views');
hbs.registerPartials('./templates/partials');
app.use(express.static('./public'));
const animal = 'Tiger';
app.get('', (request, response, next) => {
response.render('index', {
title: 'Root',
animal
});
})
app.get('/help', (req, res) => {
res.render('help', {
title: 'Help',
animal
})
})
app.get('/help/*', (req, res) => {
res.render('404', {
title: '404',
animal,
error: 'Help Page Not Found!'
})
})
app.get('*', (req, res) => {
res.render('404', {
title: '404',
animal,
error: 'Page Not Found!'
})
})
app.listen(3000, () => {
console.log("Server is on port 3000");
})
index.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<title>Root</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
{{>info}}
{{>animal}}
</body>
</html>
help.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<title>Help</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
{{>info}}
{{>animal}}
</body>
</html>
404.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<title>404</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
{{>info}}
{{error}}
{{>animal}}
</body>
</html>
animal.hbs
<p>Animal is {{animal}}</p>
info.hbs
<h1>{{title}}</h1>
Root
Help
styles.css
body {
background-color: teal;
}
I have tried explaining the question as best as possible. Please do comment if anything is not clear. Thank you so much.
app.get('/help*', (req, res) => {
res.render('404', {
title: '404',
animal,
error: 'Help Page Not Found!'
})
})
Does removing the / before the * do the trick?
Everything is in this url:
https://developers.facebook.com/tools/debug/sharing/?q=https%3A%2F%2Fweally.org%2Fentity%2F5dcac229156b765cb8c45148%2Fissue%2F5dcac2085b0a145d1f08d16e
If you go to the page facebook is testing and lookup the source code, the meta tags are present (they are even duplicated, but that's another issue)
https://weally.org/entity/5dcac229156b765cb8c45148/issue/5dcac2085b0a145d1f08d16e
here's my _document.js file : I tried to enforce the tags on the first load in ssr
import React from 'react';
import Document, {Head, Main, NextScript} from 'next/document';
import {ServerStyleSheets} from '#material-ui/styles';
import theme from '../src/theme';
import {getIssueImageSrc} from "../src/utils/util";
import DeveloperError from "../src/error/DeveloperError";
const ISSUE_URL_PREFIX = '/entity/';
function isIssuePath(path) {
return !path.startsWith(ISSUE_URL_PREFIX) && path.indexOf('/issue/') != -1
}
function getIssueIdFromPath(path) {
const startIndex = path.indexOf('/issue/') + '/issue/'.length
let otherParam = path.indexOf('/', startIndex);
if (otherParam == -1) otherParam = path.length
const issueId = path.substr(startIndex, otherParam - startIndex)
console.log("issue id for paht ", path, " is : ", issueId)
return issueId
}
class MyDocument extends Document {
render() {
return (<html lang="en">
<Head>
<meta charSet="utf-8"/>
{/* Use minimum-scale=1 to enable GPU rasterization */}
<meta
name="viewport"
content="minimum-scale=1, initial-scale=1, width=device-width, shrink-to-fit=no"
/>
{/* PWA primary color */}
<meta name="theme-color" content={theme.palette.primary.main}/>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons"/>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
/>
{this.props.desc && <meta property="og:description" content={this.props.desc}/>}
{this.props.desc == null && <meta property="og:description"
content="Make your complaint about any company visible to the entire world on WeAlly.org. We can finally look at the problems companies have with their customers, complain on WeAlly and join the responsible citizens"/>}
{this.props.image && <meta property="og:description" content={this.props.image}/>}
{this.props.image == null && <meta property="og:image" content={'https://weally.org/static/images/fb_splash.jpg'}/>}
{this.props.title && <meta property="og:title" content={this.props.title}/>}
{this.props.title == null && <meta property="og:title" content="Allied together, our complaints are powerful"/>}
<link rel="icon" href="/static/images/favicon.ico"/>
<script language="JavaScript" type="text/javascript" src="/static/js/scripts.js">
</script>
<meta property="og:url" content={`https://weally.org`}/>
<meta property="og:type" content="website"/>
</Head>
<body>
<Main/>
<NextScript/>
</body>
</html>);
}
}
MyDocument.getInitialProps = async ctx => {
// Resolution order
//
// On the server:
// 1. app.getInitialProps
// 2. page.getInitialProps
// 3. document.getInitialProps
// 4. app.render
// 5. page.render
// 6. document.render
//
// On the server with error:
// 1. document.getInitialProps
// 2. app.render
// 3. page.render
// 4. document.render
//
// On the client
// 1. app.getInitialProps
// 2. page.getInitialProps
// 3. app.render
// 4. page.render
// Render app and page and get the context of the page with collected side effects.
const sheets = new ServerStyleSheets();
const originalRenderPage = ctx.renderPage;
ctx.renderPage = () => originalRenderPage({
enhanceApp: App => props => sheets.collect(<App {...props} />),
});
const initialProps = await Document.getInitialProps(ctx);
const metaTags = {}
if (!process.browser) {
const path = ctx.asPath
if (path.startsWith(ISSUE_URL_PREFIX)) {
try {
const issueId = getIssueIdFromPath(path)
const mongoose = require('mongoose')
const Complaint = mongoose.model('Complaint')
const complaint = await Complaint.findById(issueId)
metaTags.image = getIssueImageSrc(complaint)
metaTags.desc = complaint.desc
metaTags.title = complaint.title
} catch (e) {
console.log( "Error in meta data prefetching ", e )
}
}
}
const propsToReturn = {
...metaTags,
...initialProps, // Styles fragment is rendered after the app and page rendering finish.
styles: (<React.Fragment>
{initialProps.styles}
{sheets.getStyleElement()}
</React.Fragment>),
}
return propsToReturn
}
export default MyDocument;
I naturally double checked, that the tags are inserted by this code, and they are.
Any ideas please, facebook is always falling back to the "default values" that are not relevant at all for that kind of urls. Also notice that facebook debugger is complaining about og:image that he doesn't seem to see at all
Have problem in my express app. Have some ejs templates, where css style file applied correctly. For example "localhost***/page", but when i go to "localhost***/page/secondpage" my ejs doesn't see style even if i apply it.
A little bit of code
app.js
app.use(express.static(path.join(__dirname, 'public')));
//some code
app.use('/', require('./routes/index'));
app.use('/events', require('./routes/events'));
some routes
const express = require('express');
const router = express.Router();
router.get('/', function (req, res, next) {
let query = *db query*;
res.locals.connection.query(query, function (error, results, fields) {
if (error) throw error;
res.render('index', { title: 'Events', data: results });
});
});
router.get('/:id', function (req, res) {
let query = *db query*;
res.locals.connection.query(query, function (error, results, fields) {
if (error) throw error;
res.render('singleevent', { title: 'Event', data: results });
});
});
Head of localhost***/events page and of next page localhost***/events/singleevent
<head>
<meta charset="UTF-8">
<title>
<%= title %>|Minsk Events</title>
<link rel="stylesheet" href="css/style.css">
</head>
There are my dirs
You asked for css file related to the html file.
So if html file is placed under events, then css file should be at:
/events/css/style.css
etc.
I recently start learning node.js, and I got problem. I use express to acces my public file, everything work fine except css files. I did some research on the topic, and use everthing i found, but it dose not work.
My folder structure
app.js
pub
index.html
style.css
This is my html:
<!DOCTYPE html>
<html >
<head>
<title> Curriculum Vitae </title>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css"/>
</head>
<body>
...
</body>
</html>
And my app.js file:
var http = require('http');
var url = require('url');
var fs = require('fs');
var express = require('express')
var app = express();
var path = require('path');
app.use(express.static(path.join('pub', 'public')));
http.createServer(function (req, res) {
var q = url.parse(req.url, true);
var filename = "." + q.pathname;
fs.readFile(filename, function(err, data) {
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'});
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
return res.end();
});
}).listen(8080);
I think your problem is on this line :
app.use(express.static(path.join('pub', 'public')));
You are setting "/pub/public" as public folder, and you just need to set "/pub"
Can you try with something like this ?
app.use(express.static(__dirname + '/pub'));
Hope it helps.
I need some help in accessing query string from index.html in Angular2 component. I have followed this link but it did not work for me
link
my index.html
<!doctype html>
<html>
<head>
<base href="/">
<!-- css importd -->
</head>
<body>
<app-root>Loading .. </app-root>
</body>
</html>
app.component.ts
...
public constructor(private activatedRoute:ActivateRoute) {}
ngOnInit() {
this.activateRoute.queryParams.subscribe((params:Params) => {
console.log(params['code']);
});
}
And I am invoking url http://localhost:8080/?code=test
Try this:
constructor(private route: ActivatedRoute) { }
ngOnInit() {
// get param
let paramcode = this.route.snapshot.queryParams["code"];
}
Try this :-
this.activateRoute.queryParams.subscribe(queryParams =>
console.log(queryParams['code']);
);
Add your html is code :-
<router-outlet></router-outlet>