Serve up Static Image Koa.js - node.js

I'm returning a value in JSON for example in one of my endpoints:
{
"image":"http//devservername/assets/someimage.jpg"
}
I'm trying to figure out how to statically serve this through Koa.js and not sure if that's going to be in a route or what...

Use koa-static.
npm install --save koa-static
// index.js or whatever
var KoaStatic = require('koa-static');
app.use(KoaStatic('assets'));
This will serve a request for foo.txt from assets/foo.txt. If you want to serve assets/foo.txt in response to a request for assets/foo.txt, then call KoaStatic('.'). That is probably not a good idea, since it will serve anything from the root. Better to create a public directory, put an assets directory under it, and use KoaStatic('public').

remove http://devservername and it will link, ofcourse you should use middleware to serve folders.
use koa-static-folder
import serve from 'koa-static-folder';
serve(__dirname + '/public/');

Related

Nodejs file direct access in browser

At Plesk server there are nodejs and reactjs build on hit url the build run but when we hit the nodejs file url of js files it open directly on browser means nodejs files are not secure.
So, it sounds like you are using express.static(), yet the user is able to fetch your server files that are not meant to go to the client. That apparently means that you've pointed express.static at a directory that contains your server files. Instead, you need to point express.static() at a directory hierarchy that ONLY contains files meant to be sent to the client. That means it has to be a separate directory from your server files and it has to not be above your server files directory.
There are many possible places to put it. Here are a couple ways to organize things:
projectDirectory
serverFiles
server.js
clientFiles
index.html
login.html
Then, when running server code from the serverFiles directory, you would use an express.static() like this:
const path = require('path');
app.use(express.static(path.join(__dirname, "../clientFiles")));
Or, you can do it like this:
projectDirectory
serverFiles
server.js
clientFiles
index.html
login.html
const path = require('path');
app.use(express.static(path.join(__dirname, "clientFiles")));
The idea is that the clientFiles directory hierarchy contains only client-side files and express.static() by default will not allow ../ syntax in the URLs to go above it.

How to deploy Front & Back node.js on the same Heroku app?

To be able to run my app, I need to run these 2 command in 2 different terminal :
cd app && npm install & npm start
cd api && npm install & npm start
I basically launch the front (app) and the back (api).
I want to deploy that on Heroku, but using the free plan.
Is there a way to do that? Do I need to create a package.json file on the root folder? If yes what should be inside?
Whatever I write, it seems to run only the front and never the back.
Many thanks!
You need to build the front-end and then serve it from the server end.
Whatever front-end framework you are using, make sure the build file is kept in the server static directory. Then make a route to load the build file (in most cases index.html).
Your steps might be
First, build the production-ready front-end (in most cases, it will generate the index.html in a distribution directory).
Put the distribution directory in your server public or static directory.
Make route in your server end and server the static file (mainly the index.html)
Now you are ready to go, put the node server to heroku.
For example, your final route might be
app.get("*", (req, res) => {
res.sendFile("static index.html file path");
})

NOde.js/Express App can't find some node_modules

I use several Node/Express modules in my app, and everything works fine for every module as long as I do const module = require('module');. I don't need to define a static path for these modules as app.use(express.static(path.join(__dirname, 'public')));.
However, for the sweetalert module, if I define in my layout.pug (base pug file) script(src="/node_modules/sweetalert/dist/sweetalert.min.js"), I get a 404 Error (not found) unless I include in app.js the following static path: app.use("/node_modules", express.static(__dirname + "/node_modules"));.
My question is: is this the normal behaviour or is it something I'm not doing right? (I'm kinda confused why I have to define a static path just for one of several modules I use.
Here's whats going on:
app.use(express.static(path.join(__dirname, 'public'))); is declaring that the public directory is accessible to the browser. You should put all your front end resources in that folder. This will help separate what can be accessed from the server and what can be accessed from the client.
When you reference script(src="/node_modules/sweetalert/dist/sweetalert.min.js") the browser throws a 404 because that file is not located in the public directory, therefore off limits to the browser.
Adding this line app.use("/node_modules", express.static(__dirname + "/node_modules")); "fixes" your issue but now exposes all your node_modules to the browser. This probably isn't a good idea and I'm sure a security expert could elaborate why this shouldn't be done.
How I would resolve this issue: Go through your .pug code and look at any resources your front end requires. Then copy them over to the public folder and fix your references to use the copy of the resource.
Here's an example of a script I use to move resources from the node_module directory to a public/assets directory:
build.js:
const path = require('path');
var fs = require('fs');
const ASSETS = [
'jquery/dist/jquery.min.js',
'sweetalert/dist/sweetalert.min.js'
];
if (!fs.existsSync('./public/assets')){
fs.mkdirSync('./public/assets');
}
ASSETS.map(asset => {
let filename = asset.substring(asset.lastIndexOf("/") + 1);
let from = path.resolve(__dirname, `./node_modules/${asset}`)
let to = path.resolve(__dirname, `./public/assets/${filename}`)
if (fs.existsSync(from)) {
fs.createReadStream(from).pipe(fs.createWriteStream(to));
} else {
console.log(`${from} does not exist.\nUpdate the build.js script with the correct file paths.`)
process.exit(1)
}
});
then I update my package.json to include this in the scripts:
package.json:
"scripts": {
"build": "node ./build.js || true",
"start": "node ./bin/www"
}
then in any of my views pages I reference the resource by using the new path
random.pug:
script(src="/assets/jquery.min.js")
script(src="/assets/sweetalert.min.js")
Finally before you deploy your app you now must run the following command:
npm run build then npm start
You will only need to run the build command if your front end resources change. So if you only ever use sweetalert.min.js you will only need to run the build the first time you run your app. If later on you add another resource aNewResource.js you will need to update the build.js file and run npm run build again.

vue files without NodeJS?

I want to host my app outside of node JS, but I want to use .vue files and possible npm as build system (if it's needed). Is it's possible to do?
I do not need any backward compatibility and if it work on latest Chrome dev it's ok for me.
Is there any examples how it can be done?
I tried to build some webpack template, but it's work only inside NodeJS. On other server I am getting 404 when I am accessing to URLs that placed in .vue files. It's seems that they can't be handled by the other server.
VueJS app is not NodeJS app.
VueJS app is interpreted by the browser.
You just have to build your app on computer and host files as any static website, so any server can serve html and files.
To build your app use e.g. Webpack (https://github.com/vuejs-templates/webpack )
NodeJs only use to build *.js files in front-end, your WebApp dosen't have to run on Nodejs.
1, You can create a index.html file that requires *.js file when webpack built it.
2, Use Chrome to open your index.html file so you can see it works.
You don't need to use vue-cli or other servers if you only want a static page.
But you have to know how to set your webpack.config.js, you can look that doc https://webpack.js.org/guides/getting-started/
Your starting point is wrong. Vue + node.js can build a complete site. Vue is the front-end framework, node's server language. The two can be used in combination. But not vue must rely on node to use. The two of them can be perfect to achieve the front and back separation of the development model.
In projects that use vue, individuals do not recommend configuring webpack and vue-loader separately. You can directly use vue official scaffolding, vue-cli. Do not have to consider these configurations, automatically configured.
Vue-cli
If you just started learning Vue, here's an entry-level demo. Although it is only a small application, but it covers a lot of knowledge points (vue2.0 + vue-cli + vue-router + vuex + axios + mysql + express + pm2 + webpack), including front-end, back-end, database and other sites Some of the necessary elements, for me, learning great significance, would like to encourage each other!
Vue Demo
Best way to develop Vue app is run dev server, and after all just build static assets. You don't need use vuex files, even better is use static template because you can easily integrate it with some back-end (WordPress or whatever).
Helpfully will be use some starter, for ex. Vue.js starter
It's true that vue will create static html pages when you run the build script. However, you will need to serve the files from a small server for the site to work. If you notice, when you run npm run build, the terminal will print a notice...
Tip:
Built files are meant to be served over an HTTP server.
Opening index.html over file:// won't work.
You can create a simple http server in your /dist directory with express and then host your site somewhere like Heroku.
Take a look at this article https://medium.com/#sagarjauhari/quick-n-clean-way-to-deploy-vue-webpack-apps-on-heroku-b522d3904bc8#.4nbg2ssy0
TLDR;
write a super simple express server
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
app = express();
app.use(serveStatic(__dirname));
var port = process.env.PORT || 5000;
app.listen(port);
console.log('server started '+ port);
add a postinstall script in a package.json within /dist
{
"name": "myApp",
"version": "1.0.0",
"description": "awesome stuff",
"author": "me oh my",
"private": true,
"scripts": {
"postinstall": "npm install express"
}
}
push only your /dist folder to heroku after you've compiled your site.
proof: I've followed these steps to host my vue.js project
using vue files without NodeJS (nor webpack) is possible with vue3-sfc-loader.
vue3-sfc-loader
Vue3/Vue2 Single File Component loader. Load .vue files dynamically at runtime from your html/js. No node.js
environment, no (webpack) build step needed.
vue3-sfc-loader will parse your .vue file at runtime and create a ready-to-use Vue component.
disclamer: author here
Could you try something as simple as an S3 bucket setup for web serving? How big is your project? How much traffic do you think you'll get? If it's very small, you may be able to host on S3 and use webpack, etc.

express not sending static directory

I'm trying to serve a vue.js single page app with a node.js server but I'm having an issue with some express middleware.
Basically I'm trying to serve two things right now. My index.html and a dist folder that holds all of my static files. On localhost my index.html is served correctly but I'm getting a GET error for my dist folder and can not find it in the sources tab.
I've used more or less this same line of code for many single page apps before to serve my static assets but for some reason with this set up it's not serving the dist folder.
app.use(express.static(path.join(__dirname, '/dist')));
Anyone with express experience know why this line isn't working?
You are using express.static incorrectly. By default, express.static will serve the content you have INSIDE of that dist folder.
What you want to do is this:
app.use('/dist', express.static(path.join(__dirname, '/dist')));
This will force express to serve those static assets under the '/dist' route.

Resources