I’m running a NodeJS server with Express, using Handlebars as the engine.
app.use(express.static(publicDirPath))
(...)
app.engine("hbs",hbs({
extname: "hbs",
defaultView: "main",
layoutsDir: path.join(srcDirPath, "views/layouts"),
partialsDir: path.join(srcDirPath, "views/partials"),
}));
(...)
app.listen(3000, () => {
console.log("Server started at port 3000.");
});
I have a login page:
app.get("/Login", (req, res) => {
res.render("Login", { layout: "Loginlayout" });
});
app.get("/public/js/login.js", (req, res) => {
res.header("Content-Type", "application/javascript")
res.end();
});
– which is using this header:
<head>
<script src="/public/js/login.js" async></script>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<link rel="stylesheet" href="css/login.css">
<title>Login</title>
</head>
– but I cannot use any of the functions from in login.js.
I also got some "MIME type (“text/html”) mismatch" errors, but I think I fixed them by using
res.header("Content-Type", "application/javascript")
– but I still can’t use any of the functions. I also tried multiple browsers, but nothing worked.
Let app.use(express.static(publicDirPath)) play it's role. Move local js/css file under publicDirPath dir, the express will serve assets' path for you.
Related
I'm hosting a Vue.js app on a Node.js Express app which works perfectly when running locally. When I upload it to cPanel, it only loads the index.html leaving me with a blank page and several 404 errors for all the "missing" files which are sitting next to it.
NODE: app.js
const express = require("express");
const cors = require("cors");
const path = __dirname + '/client';
const app = express();
app.use('/', express.static(path));
app.use(cors({ origin: '*' }));
app.get('/test', function (req, res) {
res.send("API TEST!");
});
// set port, listen for requests
const PORT = 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
NODE: package.json
{
"name": "basic_node_app",
"version": "1.0.0",
"description": "A Basic Node App to serve something.",
"main": "app.js",
"author": "",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.17.1"
}
}
VUE: index.html
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="icon" href="/favicon.ico">
<title>basic_vue_app</title>
<link href="/js/app.62f5dd50.js" rel="preload" as="script">
<link href="/js/chunk-vendors.2b964eb5.js" rel="preload" as="script">
</head>
<body><noscript><strong>We're sorry but basic_vue_app doesn't work properly without JavaScript enabled. Please enable it
to continue.</strong></noscript>
<div id="app"></div>
<script src="/js/chunk-vendors.2b964eb5.js"></script>
<script src="/js/app.62f5dd50.js"></script>
</body>
</html>
VUE: App.vue
<template>
<div>
<label>THIS IS A GOOD TEST</label>
<label>API WORKS -> {{ apiresult }}</label>
</div>
</template>
<script>
import Axios from "axios";
export default {
name: "App",
data() {
return {
apiresult: "",
};
},
mounted() {
Axios.get("/test").then((res) => {
this.apiresult = res.data;
});
},
};
</script>
<style>
</style>
VUE: dist folder
JS folder
app.[id].js
app.[id].js.map
chunck-vendors.[id].js
chunck-vendors.[id].js.map
favicon.ico
index.html
on my cPanel, this is my structure:
image1
I'm running the node app like this:
image2
Finally, my problem. When I run it locally I get this on my browser:
image3
But when I deploy it and run it on cPanel I get:
image4
Thanks in advance for all your help.
Best regards,
I'm trying to use contextBridge in Electron, but I keep getting an error when I try to require('jQuery') in preload.js. Here is my preload.js:
const { contextBridge, ipcRenderer } = require('electron')
require('jQuery')
contextBridge.exposeInMainWorld(
'ipcRenderer',
{
send: (channel, arg) => ipcRenderer.send(channel, arg),
on: (event, data) => ipcRenderer.on(event, data)
}
)
As soon as I put require('jQuery'), I get this error:
I want to import APIs like this since it improves security and contextIsolation will be enabled by default in later versions of Electron.
I have no idea if this is secure or not, but I just imported jQuery from index.html:
<head>
<meta charset="UTF-8">
<title>Gemini</title>
<meta http-equiv="Content-Security-Policy" content="script-src 'self'">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="macos.css">
<script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="node_modules/#fortawesome/fontawesome-free/css/all.css">
</head>
My app structure is following:
-gulp
-src
-app
-assets
-css
I want to insert files from "css" folder in index.html which is in "src" folder.
use the below code and set the path accurately.
var inject = require('gulp-inject');
var $ = require('gulp-load-plugins')({ lazy: true });
gulp.task('inject', function () {
var injectStyles = gulp.src(['css/*.css'], { read: false } );
return gulp.src( '/src/index.html')
.pipe($.inject(injectStyles, { relative: true }))
.pipe(gulp.dest('/src'));
});
specially you need to enter styles comment tag in your html file as below:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<!-- inject:css -->
<!-- endinject -->
</head>
I have pushed my angular 2 app on heroku but it takes too long to load.
is there a way to bundle everything up because right now i have this in my index.html
<html>
<head>
<base href="/">
<title>Angular 2 Arc</title>
<link rel="icon" type="image/x-icon" href="favicon.ico">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<ng2-app>Loading...</ng2-app>
<!-- Load Angular 2 Core libraries -->
<script src="es6-shim/es6-shim.min.js"></script>
<script src="systemjs/dist/system-polyfills.js"></script>
<script src="angular2/bundles/angular2-polyfills.js"></script>
<script src="systemjs/dist/system.src.js"></script>
<script src="rxjs/bundles/Rx.js"></script>
<script src="angular2/bundles/angular2.dev.js"></script>
<script src="angular2/bundles/router.dev.js"></script>
<script src="angular2/bundles/http.js"></script>
<!-- Load Bootstrap and Jquery -->
<script src="lib/jquery/jquery.min.js" charset="utf-8"></script>
<script src="lib/bootstrap/js/bootstrap.min.js" charset="utf-8"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/github-fork-ribbon-css/0.2.0/gh-fork-ribbon.min.css" />
<link rel="stylesheet" href="/lib/bootstrap/css/bootstrap.min.css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="assets/css/app.css">
<!-- Configure SystemJS -->
<script>
System.config({
defaultJSExtensions: true,
packages: {
boot: {
format: 'register',
defaultExtension: 'js'
}
}
});
System.import('js/boot')
.then(null, console.error.bind(console));
</script>
</body>
</html>
My setup is express server and system JS.
server.js
var express = require('express');
var bodyParser = require('body-parser')
var fs = require("fs");
// initialize express
var app = express();
// declare build and node_module paths
app.use(express.static("./build"));
app.use(express.static("./node_modules/"));
// parse request body
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
var body;
// route to send json data from angular 2
app.post('/export', function(req, res){
body = req.body;
res.json("Got the data!");
fs.writeFile('parameters.json', JSON.stringify({body}, null, 4), function (err) {
if (err) return console.log(err);
console.log('Data json file created!');
});
});
// start server
app.listen(process.env.PORT || "3001", function(){
console.log("Express server running on localhost:3001");
});
If its the free heroku tier its probably because its sleeping when you request it?
You can minify and concatenate your js files to decrease load times.
Here is a guide on how to do that with gulp tasks:
https://caveofcode.com/2016/03/gulp-tasks-for-minification-and-concatenation-of-dependencies-in-angularjs/
I'm learning app testing at the moment, using this course: https://code.tutsplus.com/courses/angularjs-for-test-driven-development/
I'm on lesson 2.3 where we have Mocha and Chai installed, a test folder with main.spec.js setup and gulp task setup to serve the app and tests.
When he updated his main.spec.js file with this simple describe statement:
describe('The Address Book App', function() {
it ('should work', function() {
chai.assert.isArray([]);
});
});
It ran fine for him:
However here is my setup:
test/main.spec.js
describe('The Dashboard app', function() {
it ('should work', function() {
chai.assert.isArray([]);
});
});
Basic markup:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Mocha Spec Runner</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<link rel="icon" href="../app/favicon.ico">
<link rel="apple-touch-icon" href="../app/assets/imgs/apple-touch-icon.png">
<link href="testing.css" rel="stylesheet">
</head>
<body>
<div id="mocha"></div>
<script src="../bower_components/mocha/mocha.js"></script>
<script>
mocha.setup('bdd');
</script>
<script src="../bower_components/chai/chai.js"></script>
<script>
mocha.run();
</script>
<script src="main.spec.js"></script>
</body>
</html>
However my test file isn't displaying my first test:
Gulpfile setup, same as the authors, cept PORT numbers are different:
gulp.task('serve', function() {
browserSync.init({
notify : false,
port : 3333,
server: {
baseDir: ['app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
gulp.task('serve-test', function() {
browserSync.init({
notify : false,
port : 4444,
server: {
baseDir: ['test', 'app'],
routes: {
'/bower_components' : 'bower_components'
}
}
});
});
Any idea why my first basic test isn't running?
Everything looks right except the ordering.
Just swap the
<script>
mocha.run();
</script>
with
<script src="main.spec.js"></script>
You want to run mocha at the end when all your specs and setup is done.