How can I serve mp3 file on node js? - node.js

I am building simple web app that if the user press button, it will make sound(mp3 file in the server side).
//html file
<script>
function playSound () {
document.getElementById('play').play();
}
</script>
<body>
<audio id='play', src='http://127.0.0.1:1337/', type='audio/mpeg'
<button onclick='playSound()' class='btn btn-danger btn-circle btn-lg'>
<i class='fa fa-5x fa-fire'>
</body>
//app.js
app.get('/music.mp3', function(req, res){
ms.pipe(req, res, "/music.mp3");
});
It works if I insert online source in audio attribute, but it does not serve my local server file. How can I fix this?
Thanks in advance!

To serve static files such as images, CSS files, and JavaScript files, audio, use the express.static built-in middleware function in Express.
app.use(express.static('public'));
I've already answered such type of question. See this answer

Related

Problems running imported JS in EJS file

I made an express Nodejs server and set the static folder.
The CSS has access to the page, but the JS does not find any elements. Everything is NULL.
app.use(express.static(__dirname + '/static'))
app.get('/', (req, res) => {
res.render('index')
})
//test from clientside index.js
document.body.append('test')
<script src="js/index.js"></script>
<link rel="stylesheet" href="style/main.css">
What am I doing wrong?
Problem
DOM doesn't load yet when your JS runs. It's not related to EJS, that's just how every script works.
Solution
Add defer attribute
<script defer src="js/index.js"></script>

isolated EJS Partial files loading to the browser, but not rendering on screen

I am loading my website with no errors in the console.
I have taken a static website (that used a little vanilla js for navigation), and tried ejs, templating out the menu page, header, footer, and a reused image path for promos that repeated throughout the website. I had success with this and wanted to repeat the process with the bulky blog section.
Ultimately, I had planned to refactor my blog partials into one template that could call blogs using node's 'fs' module, but my jam up has me at a loss.
Q:Why is my page not completing its render, or rendering blank on two isolated areas of my code?
Using NODEjs Express and EJS. Everything works as would be expected, except, the final blog and the contact form render blank.
I am only using to isolate blogs in their own ejs partial file:
<%- include("../partials/blog0.ejs")%>
The page will stop rendering at "blog3.ejs" and "contact" My vanilla js still operates by using the dom to id.style.display="none" effectively
I have deconstructed and un-nested my partials out of my index.ejs almost back to its original index.html. Everything Renders except for blog3 and contact.
index.js
const express =require('express');
const ejs = require('ejs');
const app = express();
var http = require('http');
var nodemailer = require("nodemailer");
var sass =require('sass');
app.use(express.static('public'));
app.use(express.static('views'));
app.use(express.static('css'));
app.use(express.static('jsFiles'));
app.use(express.static('partials'));
//routes
app.get('/', function(req, res){
res.render('pages/index');
console.log('pages/index hit')
});
app.get('/', function(req, res){
res.render('partial/header');
console.log('partial hit')
})
app.set('view engine','ejs');
console.log('static site!! listening on:3005 started at: '+Date())
console.log('find app on: localhost:3005 ')
app.listen(3005);
http.createServer(function(req,res){
res.writeHead(200,{'Content-Type':'text/plain'});
res.end('future api dev here');
}).listen(8080);
index.ejs
<body onload="loader()">
<%- include('../partials/burgerButton.ejs') %>
<%- include('../partials/menu.ejs') %>
<%- include('../partials/header.ejs') %>
<div id="mainContent" class="content">
<!--each blog article. I had them in their own ejs file, but reversed that sonce experiencing my issue-->
<div id="blogIntro" class="blogBody">
<h1>Welcome to
<span class="logoFont"> ValRick Travel's</span>
featured Blogs</h1>
<div class="card">
*blog article*
</div>
</div>
Turns out my old method using vanilla JavaScript was interfering with a display property = "none".
I removed id handlers in my scss and found EJS had been working exactly as I had programmed it.....to hide the until the user called for it.
The error was in my jsFiles during migration from a static vanilla website over to express and ejs.

Receive data from an HTML page, after receiving the information from the server by Nodejs

There is a site that has a page with a form that by submitting the form with the POST method, an HTML page is received and this received page has a LOADING and a few seconds later the LOADING is completed and the data is received. How can I do this in nodejs and get the data?
https://tracking.post.ir/?id=221670002100060770073113
To get you started, you'll need a few things: express, socket.io and some HTML code.
First, you'll need to install 2 essential node packages
npm install express socket.io --save
Secondly, you'll need to create a web server. Below is a very basic example:
const express = require('express'); // Define express
const app = express(); // Define the web app
const server = require('http').createServer(app); // Define the HTTP server
const io = require('socket.io')(server); // Define socket.io
app.get('/my/route', function(req, res) { // Listen for an incoming request
res.sendFile('/path/to/your/loading-page.html'); // Render your HTML loading file
// Load some data
io.emit('data-loaded', 'your-data'); // Emit your data to the client
});
server.listen(3000, () => console.log('Server is online'); // Allow your server to listen for incoming traffic
Now, you need to setup the receiving end (the client). In this example case this is the loading file
<!DOCTYPE html>
<html lang="en">
<body>
<!-- Some HTML code -->
</body>
<script src="/socket.io/socket.io.js"></script> <!-- Don't change this -->
<script>
let socket = io.connect(); // Connect to the server
socket.on('data-loaded', function() { // When the data has been loaded
// Do something with the HTML page
});
</script>
</html>
References:
- express docs
- socket.io docs
Hei, node.js is a JavaScript framework that works in the server-side of web applications. Like PHP.
You'd need to firstly create a node project setting up a node server.
getting started on node
to get POST parameters on node.js, you use request.body.name
where 'name'' stands for the name in the input field you have in the HTML form, just like the example below
<form action="yourAction">
<input type="text" name='yourName'>
<input type="submit" value='form'>
</form>
and in the node.js part, you type something like this
app.get('/yourAction', function(request, response){
console.log(request.body.yourName)
})

Node.js web app uploaded through A2 Hosting - pathing issue with CSS

I am currently studying node.js and pretty new still so I apologize in advance for probably having an inefficient or terribly formatted first question. I am uploading a one-page test to figure out how to use A2's node.js service.
So far I have followed the A2 tutorial "How to create a Node.js application with cPanel using Node.js Selector" (https://www.a2hosting.com/kb/cpanel/cpanel-software/create-application-with-nodejs-selector) and this tutorial on syncing git repositories (https://medium.com/#pampas93/host-your-node-js-app-on-shared-hosting-go-beyond-localhost-73ab923e6691) and I have been able to get everything working except the main page
(Located in dirname/repositories/test/views/home-visitor.ejs)
will not read the CSS file I have uploaded
(Located in: dirname/repositories/test/public/main.css)
and some of the images do not load. No file name typos or forward slash "/" syntax inconsistencies, all images share the same folder path.
(Located in: dirname/repositories/test/public/images)
So the node.js app shows up as plain HTML only. I have uploaded the exact same app/git repository to Heroku and the CSS is read and all images show up, so I am trying to figure out what pathing issues I am having when uploading specifically to A2's hosting service.
When I check 'inspect' on the browser for the non-working app page, I get these console messages:
"Refused to apply style from 'http://domainname.com/main.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled."
Failed to load resource: the server responded with a staus of 404 () nonWorkingImageExample.png:1
Failed to load resource: the server responded with a staus of 404 () anotherNonWorkingImageExample.png:1
http://domainname.com/test/main.css sends to a 404 page
app.js:
const express = require("express")
const app = express()
let port = process.env.PORT
if (port == null || port == "") {
port = 3000
}
app.use(express.static("/public/"))
app.set("views", "views")
app.set("view engine", "ejs")
app.get("/test", function (req, res) {
res.render("home-visitor")
})
app.listen(3000)
The page I am testing: home-visitor.ejs:
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="main.css" type="text/css">
</head>
<header>
<div class="forMobile mobileHeader">
<div class="mobileLogo">
<a href="#"><img src="images/workingImageExample.png" alt="Image Description">
</a>
</div>
</div>
</header>
<div class="forDesktop centerContent tempMssg">"Lorem flexitarian salvia offal umami. Sartorial swag drinking portland cray. Godard jianbing retro thundercats hella tilde. "
<br><br>
<a href="#" target="_blank" rel="noopener noreferrer">
<img src="images/nonWorkingImageExample.png" alt="Twitter Logo Link" width="35px" height="35">
</a>
</div>
<div class="forMobile mobileUpperBG">
<img src="images/anotherNonWorkingImageExample.png" alt="upper left bg image">
</div>
</html>
I am hoping someone familiar with hosting node.js apps on A2 can help, and thank you for the time reading this question regardless.
Full credit for this solution goes to VictoryFlame's video
https://www.youtube.com/watch?v=BAD5JyOymRg.
I ended up editing the way app.js pathed my public folder and updated how I linked the CSS and image files in my .ejs file:
app.js:
const express = require("express")
const app = express()
const path = require("path")
app.set("views", path.join(__dirname, "views"))
app.set("view engine", "ejs")
app.use("/test1/static", express.static("public/"))
app.get("/test1", function (req, res) {
res.render("home-visitor")
})
app.listen()
I re-formatted the style link to the CSS page and used this pathing syntax for images:
home-visitor.ejs:
<link rel="stylesheet" href="https://domainname.com/test1/static/home.css">
<a href="#" target="_blank" rel="noopener noreferrer">
<img src="/test1/static/images/imageWorksNow.png" alt="Twitter Logo Link" width="35px" height="35"></a>
Now everything is properly served/linked and showing up. I hope this helps someone else some day!

Captcha in MEAN js

I need to use Captcha in MEAN js login. I need the simplest possible way to make it work. I saw Visual Captcha but I'm not able to understand where should I use it in the MEAN js application.
I need an offline captcha solution on MEAN js app. I plan to deploy it on a raspberry pi.
You can use google recaptcha with external script file in mean stack page. There is a js code.
https://developers.google.com/recaptcha/docs/display#js_api
Just follow this.
<script type="text/javascript">
var onloadCallback = function() {
grecaptcha.render('html_element', {
'sitekey' : 'your_site_key'
});
};
</script> </head> <body>
<form action="?" method="POST">
<div id="html_element"></div>
<br>
<input type="submit" value="Submit">
</form>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"
async defer>
</script> </body> ```

Resources