how to code a sails http middleware for a directory? - node.js

i am using one npm package for generating QR code after it will save the image in qr directory and after i cant access the file with my app and also directly. i think it is the problem of middleware.(i can acces the images after sails restating, it is working on my localhost). each time a user using my app it will automatically generate qr for the user changes.

You have plenty of ways to do that.
Create a symlink in asset (eg: assets/app) pointing to your qrcode folder
You can access express trough sails.express. So you can add in your config/bootstrap :
var express = require('express');
sails.express.app.use(express.static(process.cwd() + '/qrcode_folder'));
Custom middleware. Add in your config/http.js :
var express = require('express');
module.exports.express = {
qrCodeMiddleware: function (app) {
app.use(express.compress());
app.use('/qrcode', express.static(process.cwd() + '/my_qrcode_folder'));
}
};

Related

How to fix needing to reload my api in nuxt every time i change my api?

I connected an express api to the nuxt servermiddleware: ['~/api/index'] in the nuxt.config.js file. but if i'm dev building my api, i don't want to reload the dev server manually every single time i change something in the code (that costs a lot of time). It looks like the api runs independent from the nuxt.js website. if the website reloads, the api won't and the changes will not show. Is there a way that the api reloads when the website reloads?
my code in the index.js of the api is this:
const express = require('express')
const app = express()
const bodyParser = require("body-parser")
app.use(bodyParser.json())
// Require API routes
const company = require('./routes/company')
// Import API Routes
app.use('/company', company)
// Export the server middleware
module.exports = {
path: '/api',
handler: app
}
i hope its more clear now.
In the components folder edit your config to be like
{
// this avoids reloading all components every time you run the app
components: false
}

Is it possible to host web page with angular.min.js functionality using nodes http module

Is it possible to host web page with angular.min.js functionality using nodes http module?
I'm making a really simple web project that is going to fetch some data and I decided to use angular.js to display data no the page. I tried to read index.html using fs module and sent it as response to the localhost. It seems that angular.min.js, that was included in the pages head section did not load as it would when I run the page in the browser from the file explorer.
angular is a web application, so, please serve the angular using your node.js server and load the app in the web browser.
add a listener of get then send all files that index.html need, it is done.
or use app.use(express.static('public')); which public is your 'public' folder, put all file in dist to serve as a static content.
I use the first option every time but it is trick but functional.
sample code is:
const express = require('express');
const router = express.Router();
const path = require('path');
router.get('/:id',(req,res)=>{res.sendFile(path.join('/path/to your/file/'+req.params.id));});
router.get('/',(req,res)=> res.sendFile(path.join('/path/to/your/file/index.html'));});
module.exports = router;

How to create a node based server to serve REST API and also deploy the application.

I am new to nodeJS server area, need help in understanding how to work with REST API (using express) and deploy the angular application over a singe node server and same ports.
By deploying i want to understand if user hit below url http://localhost:8000/<page_name> then the specified page should open.
And is user hit below url using get or post request
http://localhost:8000/api/<api_name> then a json or a text will be returned.
How to run both the thing over a single node server.
Lets assume, you have all your static files in the /public folder of you app. Generally spoken, if you are using express.static, you should also get your index.html because this is handled by default for each directory.
In your case, as you are using Angular, the routing is handled from the client side (SPA). You should only have one single index.html after building your Angular app. All files from your dist folder should then be placed into your /public folder. Then you need to make sure, that initial file serving provides your index.html like so:
In this example static files are served first, then your API and if nothing is found, you are getting back you index file.
const express = require('express');
const app = express();
// serve static files
app.static(__dirname + '/public'));
// serve your API
app.get('/api/welcome', function (req, res) {
res.send('Welcome');
});
// fallback routing (server side handling)
app.get(/.*/, function (req, res) {
res.sendFile(__dirname + ‘/public/index.html‘
});
app.listen(3000);
Next time please make sure, to give all necessary information in your question ;-)
With the help from Sebastian, so far I can find a solution but its not working when i am hitting URL for different pages.
const express = require('express');
const app = express();
app.use(express.static('public'))
Please provide your suggestions.

Generate Swagger Document for existing NodeJS server

According to Swagger website, there are two approaches: Bottom-up and Top-down.
I have an existing NodeJS server that I'd like to deploy in the Azure enviroment, that require a swagger document (API APP).
Does anyone know a tool for generating the swagger using the code? Even better if you could point a tutorial. I couldn't find it.
Question is a bit old but still. It is possible to generate completely automatically Swagger (OpenAPI) specification just by embedding analysis middleware like this: https://github.com/mpashkovskiy/express-oas-generator
const express = require('express');
const expressOasGenerator = require('express-oas-generator');
let app = express();
expressOasGenerator.init(app, {});
run some client or REST API tests agains your service and open http://host:port/api-docs
It’s not difficult to integrate Swagger in exist express applications following this tutorial.
Generally, we can follow these steps:
Add the dependencies in our package.json, and run npm install to install them. The dependencies should be:
"dependencies": {
"swagger-node-express": "~2.0",
"minimist": "*",
"body-parser": "1.9.x",
...
}
Download the zip project of Swagger-UI, copy the dist folder into the root directory of our project, the directory should almost like:
Introduce the dependencies at the beginnng of app.js:
var argv = require('minimist')(process.argv.slice(2));
var swagger = require("swagger-node-express");
var bodyParser = require( 'body-parser' );
Set up a subpath for swagger doc:
var subpath = express();
app.use(bodyParser());
app.use("/v1", subpath);
swagger.setAppHandler(subpath);
Make sure that /dist is able to serve static files in express:
app.use(express.static('dist'));
Set the info for API:
swagger.setApiInfo({
title: "example API",
description: "API to do something, manage something...",
termsOfServiceUrl: "",
contact: "yourname#something.com",
license: "",
licenseUrl: ""
});
Introduce /dist/index.html for swagger UI:
subpath.get('/', function (req, res) {
res.sendfile(__dirname + '/dist/index.html');
});
Complete the swagger configurations:
swagger.configureSwaggerPaths('', 'api-docs', '');
var domain = 'localhost';
if(argv.domain !== undefined)
domain = argv.domain;
else
console.log('No --domain=xxx specified, taking default hostname "localhost".');
var applicationUrl = 'http://' + domain;
swagger.configure(applicationUrl, '1.0.0');
Configure doc file dependence in /dist/index.html:
if (url && url.length > 1) {
url = decodeURIComponent(url[1]);
} else {
<del>url = "http://petstore.swagger.io/v2/swagger.json";</del>
url = "/api-docs.json";
}
Create api-docs.json file with the info of your APIs, put it in the dist folder.
Run the Express app on local, visit http://localhost:3000/v1, we can check the swagger doc.
Here is my test sample repo for your reference.
To my knowledge, your options are:
Using swagger-node-express which is very cumbersome in my opinion.
Writing up the swagger document manually yourself with the help of swagger editor as suggested in this SO Answer
If you go for option 2, you could use swagger-ui-express to generate the swagger-ui
A lot of developers are still having this problem so I built an open-source tool to help -- the tool is kind of like Git for APIs. It works by running a proxy while you're developing the API, analyzing the traffic, and updating the spec for you as the API's behavior changes. Hopefully, the workflow saves you a lot of time: https://github.com/opticdev/optic
Most alternatives require some sort of API specification through Json, Yaml or even embedded in JSdocs. On the other hand there are some runtime analyzers intercepting HTTP requests and building that specification on-demand.
express-sitemap-html follows a different approach inspecting the express object and its routes at setup time. Thus it always provides an up-to-date swagger UI for installed routes on existing express instance.
const sitemap = require('express-sitemap-html')
...
sitemap.swagger('Title', app) // app is an express instance
Then get swagger UI from your domain /api-docs.

Download browserify bundle from node.js

I'm trying to develop node.js app with express.js. One of the thing which I try to implement is a function to serve generated by browserify bundle js file. What I would like to do is to use maven-download-plugin to download that file and put into my repository (it's java app). I know that his is a bit complicated but that's how it's look like. I can generate bundle with browserify using code:
browserify("./path/myjs.js", {
gzip : true
});
b.transform("hbsfy");
b = b.bundle({standalone: 'bundle'});
However I cannot find any information how to write that information to the public/bundle.js and how to serve it when for example path /bundle.js will be requested.
Any ideas how can I do that?
Well, why don't you just use static module for express?
var express = require('express');
var app = express();
app.use(express.static(__dirname + '/public'));
To write bundle to the file, just stream it...
var fs = require('fs');
var ws = fs.createWriteStream(__dirname + '/public/bundle.js');
b.bundle({standalone: 'bundle'}).pipe(ws);
Or you can do it completely on-fly avoiding file-system and streaming directly to client...
app.get('/bundle.js', function(req, res, next) {
b.bundle({standalone: 'bundle'}).pipe(res);
});

Resources