Jade-lang add manifest file - node.js

I would like to know how to add the manifest file to node.js site with jade-lang and express. I found this as an issue 239 in github. My question is how can I add some data into the buffer without while we wait for the resolution of the issue.
Thank's!

There's a simple way to do this in jade:
Just try this
html(manifest=_condition_ ? "cache.manifest" : undefined)
This code checks if condition is true. If it is, manifest is set to "cache.manifest". Otherwise it'll be set to undefined and dropped.

I'm going to need this in one of my projects soon, so I was curious to give it a try. There is effectively a problem if you try to do it in a single file:
!!! 5
if useManifest
html(lang="en", manifest="cache.manifest")
else
html(lang="en")
head
title sample title
body
p some content...
This renders a messed up HTML. However, the following seems to work just fine (it's definitely a workaround):
In routes\index.js :
exports.index = function(req, res){
res.render('testJade', { layout: false, useManifest: true })
};
In views\testJadeInclude.jade:
!!!5
if useManifest
html(lang="en", manifest="cache.manifest")
block content
else
html(lang="en")
block content
And finally, in views\testJade.jade:
include testJadeInclude
block append content
head
title sample title
body
p some content
Then based on whatever you wish (such as if the client is a mobile browser, or whatever), you set useManifest to true or false.
And I just tested another possibility, which is kind of the other way around. Instead of including the doctype and html tag in your content file (via a block append), you include the content file in the doctype-html file, so it looks like this:
!!! 5
if useManifest
html(lang="en", manifest="cache.manifest")
include contentFile
else
html(lang="en")
include contentFile

Related

Socket.io does not work on deploying to Heroku [duplicate]

Why am I getting this error in console?
Refused to execute script from
'https://www.googleapis.com/customsearch/v1?key=API_KEY&q=flower&searchType=image&fileType=jpg&imgSize=small&alt=json'
because its MIME type ('application/json') is not executable, and
strict MIME type checking is enabled.
In my case it was a file not found, I typed the path to the javascript file incorrectly.
You have a <script> element that is trying to load some external JavaScript.
The URL you have given it points to a JSON file and not a JavaScript program.
The server is correctly reporting that it is JSON so the browser is aborting with that error message instead of trying to execute the JSON as JavaScript (which would throw an error).
Odds are that the underlying reason for this is that you are trying to make an Ajax request, have hit a cross origin error and have tried to fix it by telling jQuery that you are using JSONP. This only works if the URL provides JSONP (which is a different subset of JavaScript), which this one doesn't.
The same URL with the additional query string parameter callback=the_name_of_your_callback_function does return JavaScript though.
This result is the first that pops-up in google, and is more broad than what's happening here. The following will apply to an express server:
I was trying to access resources from a nested folder.
Inside index.html i had
<script src="./script.js"></script>
The static route was mounted at :
app.use(express.static(__dirname));
But the script.js is located in the nested folder as in: js/myStaticApp/script.js
I just changed the static route to:
app.use(express.static(path.join(__dirname, "js")));
Now it works :)
Try to use express.static() if you are using Node.js.
You simply need to pass the name of the directory where you keep your static assets, to the express.static middleware to start serving the files directly. For example, if you keep your images, CSS, and JavaScript files in a directory named public, you can do as below −
i.e. : app.use(express.static('public'));
This approach resolved my issue.
In my case, I was working on legacy code
and I have this line of code
<script type="text/javascript" src="js/i18n.js.php"></script>
I was confused about how this supposed to work this code was calling PHP file not js
despite it was working on the live server
but I have this error on the stage sever
and the content type was
content-type: text/html; charset=UTF-8
even it is text/javascript in the script tag
and after I added
header('Content-Type: text/javascript');
at the beginning for file i18n.js.php
the error is fixed
After searching for a while I realized that this error in my Windows 10 64 bits was related to JavaScript. In order to see this go to your browser DevTools and confirm that first. In my case it shows an error like "MIME type ('application/javascript') is not executable".
If that is the case I've found a solution. Here's the deal:
Borrowing user "ilango100" on https://github.com/jupyterlab/jupyterlab/issues/6098:
I had the exact same issue a while ago. I think this issue is specific to Windows. It is due to the wrong MIME type being set in Windows registry for javascript files. I solved the issue by editing the Windows registry with correct content type:
regedit -> HKEY_LOCAL_MACHINE\Software\Classes -> You will see lot of folders for each file extension -> Just scroll down to ".js" registry and select it -> On the right, if the "Content Type" value is other than application/javascript, then this is causing the problem. Right click on Content Type and change the value to application/javascript
enter image description here
Try again in the browser."
After that I've realized that the error changes. It doesn't even open automatically in the browser anymore. PGAdmin, however, will be open on the side bar (close to the calendar/clock). By trying to open in the browser directly ("New PGAdmin 4 window...") it doesn't work either.
FINAL SOLUTION: click on "Copy server URL" and paste it on your browser. It worked for me!
EDIT: Copying server URL might not be necessary, as explained by Eric Mutta in the comment below.
I accidentally named the js file .min instead of .min.js ...
Python flask
On Windows, it uses data from the registry, so if the "Content Type" value in HKCR/.js is not set to the proper MIME type it can cause your problem.
Open regedit and go to the HKEY_CLASSES_ROOT make sure the key .js/Content Type has the value text/javascript
C:\>reg query HKCR\.js /v "Content Type"
HKEY_CLASSES_ROOT\.js
Content Type REG_SZ text/javascript
In my case (React app), just force cleaning the cache and it worked.
I had my web server returning:
Content-Type: application\javascript
and couldn't for the life of me figure out what was wrong. Then I realized I had the slash in the wrong direction. It should be:
Content-Type: application/javascript
In my case, while executing my typescript file,
I wrote:
<script src="./script.ts"></script>
Instead of:
<script src="./script.js"></script>
In my case Spring Security was looking for authentication before allowing calls to external libraries. I had a folder /dist/.. that I had added to the project, once I added the folder to the ignore list in my WebSecurityConfig class, it worked fine.
web.ignoring().antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/error", "/dist/**");
Check for empty src in script tag.
In my case, i was dynamically populating src from script(php in my case), but in a particular case src remained empty, which caused this error. Out was something like this:
<script src=""></script> //empty src causes error
So instead of empty src in script tag, I removed the script tag all together.
Something like this:
if($src !== ''){
echo '<script src="'.$src.'"></script>';
}
You can use just Use type
or which you are using you choose that file type
My problem was that I have been putting the CSS files in the scripts definition area just above the end of the
Try to check the files spots within your pages
I am using SpringMVC+tomcat+React
#Anfuca's answer does not work for me(force cleaning the browser's cache)
I used Filter to forward specific url pattern to the React's index.html
public class FrontFilter extends HttpFilter {
#Override
protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
boolean startsWithApi = requestURI.startsWith("/api/");
boolean isFrontendUri = requestURI.startsWith("/index.html");
if (!startsWithApi && !isFrontendUri) {
req.getRequestDispatcher("/index.html").forward(req, res);
}
super.doFilter(wrapped, res, chain);
}
}
There is no Spring Security problem bcs my filter executes before Spring Security's
but I still see the same error and find here
Then I realized that I forgot adding one more condition for JS and CSS:
boolean startsWithStatic = requestURI.startsWith(contextPath + "/static");
Add this to my if condition and problem solved, no more error with MIME type or ('text/html') with js and css
Root cause is that I incorrectly forward JS and CSS type to HTML type
I got the same error. I realized my app.js was in another folder. I just moved it into that folder where my index.html file is and it resolved.
In Angular Development try this
Add the code snippet as shown below to the entry html. i.e "index.html" in reactjs
<div id="wrapper"></div>
<base href="/" />
If you have a route on express such as:
app.get("*", (req, res) => {
...
});
Try to change it for something more specific:
app.get("/", (req, res) => {
...
});
For example.
Or else you just might find yourself recursively serving the same HTML template over and over...
In my case I had a symlink for the 404'd file and my Tomcat was not configured to allow symlinks.
I know that it is not likely to be the cause for most people, but if you are desperate, check this possibility just in case.
I hade same problem then i fixed like this
change "text/javascript"
to
type="application/json"
I solved my problem by adding just ${pageContext.request.contextPath} to my jsp path .
in stead of :
<script src="static/js/jquery-3.2.1.min.js"></script>
I set :
<script src="${pageContext.request.contextPath}/static/js/jquery-3.2.1.min.js"></script>

gulp-inject: missing end tag for start tag when using pug

I have a rather specific problem: I am trying to build a complex stack using Sails.js with machinepack-sailsgulpify.
In order to inject assets into my templates I use gulp-inject plugin, as the machinepack suggests. The problem is that for anything other than html and ejs the injector doesn't work. It simply doesn't change anything. No errors, nothing.
My task looks like this:
gulp.task('sails-linker-gulp:devViews', function() {
return gulp.src('views/**/*.?(html|ejs|jade|pug|haml|slim|dust)') // Read templates
.pipe(
plugins.inject(
gulp.src(require('../pipeline').jsFilesToInject, {read: false}), // Link the javaScript
{
starttag: generateScriptStartTag,
endtag: generateScriptEndTag,
ignorePath: '.tmp/public',
transform: (filepath, file, i, length) => {
return `script(src="${filepath}")`;
}
}
)
)
.pipe(
plugins.inject(
gulp.src(require('../pipeline').cssFilesToInject, {read: false}), // Link the styles
{
starttag: generateStyleStartTag,
endtag: generateStyleEndTag,
ignorePath: '.tmp/public'
}
)
)
.pipe(
plugins.inject(
gulp.src( ['.tmp/public/jst.js'], {read: false}), // Link the JST Templates
{
starttag: generateTemplateStartTag,
endtag: generateTemplateEndTag,
ignorePath: '.tmp/public'
}
)
)
.pipe(gulp.dest('views/'))// Write modified files...
Don't worry about the generateScriptStartTag and such functions, they are just there for control and I am 1000% sure they work correctly, tested a lot. They generate the tags kind of like this:
//- SCRIPTS
//- SCRIPTS END
depending on the template language.
Adding custom transform function did not work. If I use ejs or html or really anything that resembles html syntax it works fine.
Now, about Sails: I can NOT add a gulp task to compile the template before injecting because Sails renders templates on request in development, it doesn't actually pre-compile them into any directory. And honestly: why should I? The injection is just adding lines to my .jade/.pug files in views, the files are there already, so I don't see why there's a problem there. Can someone advise?
UPDATE:
Rather frustrating inspection of the code revealed that the 'matches' property when running the inject function of has length 0 and when inspecting the content of the stream in node inspector, I did not see the comments, they were stripped away, despite the fact that they are clearly there in the file.
UPDATE #2:
It appears that I was wrong about ejs. ONLY HTML files are getting processed. Also it works OK when it doesn't detect the injection comments. However if it does the end event simply never emits for that file and nothing gets injected. This is true for ALL templating engines, only static HTML files have injection working fine.
UPDATE #3:
After another 5 hours of debugging I found the problem, however my understanding of streams isn't good enough to get me any closer to the solution. The problem is that in inject function of the plugin there's a loop that doesn't quit properly, and while it perfectly injects the required tags into the stream, it then runs that loop again on the same stream (with injected tags), and throws an error.
Why that error never showed up in any console I don't know but there you go. Can someone please help? I am completely lost with this... Is it a bug in the plugin?
I had to figure this out on my own.
It is a bug in gulp-inject. The regex that this plugin generates to test against the injection tags does not match the whole line, it's simply matches the first occurrence. This means that if I have my tags set like so:
//SCRIPTS
//SCRIPTS END
The regex will match the starttag: //SCRIPTS twice:
And the end tag will only be matched once. This was causing the second faulty loop with the error for missing end tag.
A workaround is to avoid repeating start of tags.
//SCRIPTS
//END SCRIPTS
That's not a solution, however. A solution would be to alter the regex so that it only allows whitespace and newline characters in order to match the tag, when using an indent-based template language.
Something like this would work: /\/\/-\s*SCRIPTS(?=\s*\n|$)/ig
Can't believe nobody has stumbled upon this until now, seems like it would be a more common problem...

Scope of exported variable in express and jade

I'm having a few issues with Jade and scope of variables exported from the route. This might be an obvious answer, but my googling abilities have failed me.
In my route, I have this code :
res.render('index', {title: "App",
csvData: json // This is a json object
};
In my view, I want to display the length of the json object on the click of a button. My jade looks like this :
extends layout
block content
script
-var test123 = csvData;
-console.log(test123.length);
div
button.btnCSV(onclick='console.log(test123)') Save As CSV
The first console.log prints the correct length, but when I do press the button, it tells me that test123 is undefined. I think this has something to do with the difference between client side/server side variables. If that is the case, is there anyway to make a server side variable accessible to a client side scope?
I'm not sure how your example would work with the script content prefixed with a -, this indicates unbuffered code. JavaScript that runs server side and that produces no direct output, so your in-line script is most likely empty.
Similarly your onclick handler is just compiling a string on the server, which is the main problem you appear to report.
In order to achieve what you trying to do, you should define a function in the script block which can be called from your buttons onclick handler. Take care to ensure that your script keyword ends with a . so that the following lines are treated as block content of the script.
Here's what your template should look like.
extends layout
block content
script.
var test123 = !{JSON.stringify(csvData)};
function printLength() {
console.log(test123.length);
}
div
button.btnCSV(onclick='printLength()') Save As CSV
Then on the server side make sure you're returning an actual JavaScript object, or an Array, and not a string representation... it should look like this
res.render('index', {title: "App",
csvData: [{ val1: 'value1', val2: 'value2' }]
};
This allows variables to be used for server side scripting (if required) as well as client side.

Derbyjs TEMPLATE ERROR

I just started trying out Derbyjs, and I already ran into a problem. I can't find any support for this error, and most likely is some dumb mistake i'm making.
I'm trying to render a view, following the example from the www.derbyjs.com documentation.
My app is as simple as this:
var app = require('derby').createApp(module);
app.get('/', function (page, model) {
page.render('home');
});
My views are composed by two files.
"index.html"
<import: src="home">
<Body:>
Default page content
"home.html"
<Body:>
Welcome to the home page
I get the following error whenever the page is rendered:
TEMPLATE ERROR
Error: Template import of 'home'... ...can't contain content
As you can see, it is a very simple example. What am I missing?
I get that error even if I have the "home.html" file empty.
Well, I got the answer from one of the developers.
It seems like there was a subtle bug in the Template Parser that probably has already been fixed.
Having a whitespace or linebreak in front of
<import: src="home">
was causing the parser to raise the error. Writing
<import: src="home"><Body:>
solved the issue.

Passing raw Markdown text to Jade

I'm playing around with my first Node.js Express application, and as every programmer knows, the first thing you should build when testing out a new framework is a blog! Anyway, I'd like to write the articles in Markdown and then render it in the view. I saw that Jade allows for this to be done inside the view itself, using filters, but I can't get that working.
To simplify the situation, here's an example of what I'm talking about.
//app.js
res.render("article", {
md : "Hello World!\n\n*Woo*"
});
//article.jade
section
:markdown
#{md}
But, that outputs this: <section><h1>{md}</h1></section>... it isn't substituting in the variables I've passed to it.
Then I tried this:
//article.jade
section
:markdown
!{md}
And the output is this:
<section><p>Hello World!
*Woo*</p></section>
So, now it's not parsing the markdown!
I have been able to get this to work by parsing the markdown in the app.js file and then passing the HTML to the view to display, but I don't know, that seems a bit messier.
Is there a way to pass variables into Jade filters?
You can do this with a function passed in to jade from node:
var md = require("node-markdown").Markdown;
Then pass it into the view as a local:
res.render('view', { md:md, markdownContent:data });
Then render it in the jade view by calling the function:
!= md(markdownContent)
The node module node-markdown is deprecated. The marked is advanced new version. You can try like this
var md = require('marked');
Inside your router
res.render('template', { md: md });
Inside your jade template
div!= md(note.string)
I don't think jade can do this out of the box. One way to accomplish it that might feel slightly cleaner than pre-rendering the markdown is to create a helper function called markdown that takes a markdown string and returns HTML. Then you could do something like
section
!= markdown(md)
The markdown function should be included in the locals data when you render the jade template and can directly use a markdown library to convert the markdown syntax to HTML.
If you are using Scalate's Jade support you can enter:
section
:&markdown
#{md}
You can also import external files with:
section
:&markdown
#{include("MyFile.md")}

Resources