The documentation for Swagger (https://github.com/swagger-api/swagger-node) only shows how to create a new app. How do I integrate Swagger into an existing API app?
I followed this guide: https://blog.cloudboost.io/adding-swagger-to-existing-node-js-project-92a6624b855b
npm i swagger-ui-express -S
I used the Swagger editor to create a swagger.yml file. http://editor.swagger.io/
I added this to my server:
var swaggerUi = require('swagger-ui-express')
var fs = require('fs')
var jsyaml = require('js-yaml');
var spec = fs.readFileSync('swagger.yml', 'utf8');
var swaggerDocument = jsyaml.safeLoad(spec);
...
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
I was then able to access Swagger docs via http://localhost/api-docs.
It's unfortunately not the same level of integration that Swagger has with Spring Boot in Java, where you can add an annotation and Swagger will automatically generate the documentation for you. It seems Swagger for Node requires you to maintain the swagger.yml documentation manually. I have my routes defined like app.use('/users', userRouter) and inside the users.js file I have functions defined like router.post('/status', (req, res) => { ... }. That doesn't seem compatible with Swagger for Node, which has a concept of operationId which somehow points to a function name.
Related
I am creating a new Angular 4 application. I have followed it's official tutorial https://angular.io/tutorial/
The application server is started using ng serve command.
I have created a separate node js (+express) server that provides the REST services to the main app on a different port.
Is there any way to serve the main angular application from the same nodejs/express server so that i don't have to use two servers for the application?
I have used typescript which needs to be somehow compiled into plain javascript before statically being served via nodejs, if i understand it right?
Absolutely, just use ng build and serve the dist folder of the built application, or even the src. Example:
const staticFor = rel => express.static(path.resolve(__dirname, rel));
const app = express();
if (!config.production) {
app.use('/node_modules', staticFor('../node_modules'));
// In development we do not copy the files over, so map used path
}
app.use('/', staticFor('../dist/app'));
const appPath = path.resolve(
__dirname,
config.production ? '../dist/app/index.html' : '../src/app/index.html'
);
app.get('/yourAppPath/*', (req, res) => {
const markup = fs.readFileSync(appPath, 'utf8');
res.send(markup);
});
Dont forget to require the right libraries.
I currently have an Angular app (MEAN Stack) that I am running locally on my Windows machine. Being new to Node/Express, I would like to be able to access a local directory from http://localhost:3006 that I have setup within my main app directory, called /myfiles which I am unsure how to do.
What I am unsure is, how do I create an endpoint to access and read these files from localhost within the /myfiles directory and display them within an Angular Material dialog?
Just not sure what I need to do as part of Express side (setting up the route) and then the Angular side (using HttpClient) to display.
Further to the above, I will also need to write back to the /myfiles directory, where I will need to perform a copy command based on a file selection within Angular.
You'll want to create an endpoint in Express that your Angular app can call to be served the files.
I'll assume the files you want to read and send are JSON files. Here's a really simple example of an endpoint that you can visit that will return the file to your frontend.
In your Angular code you will make a get call to /myfile
var fs = require("fs");
app.get('/myFile', (req, res) => {
var filepath = __dirname + '/myfiles/thefile.json';
var file = fs.readFileSync(filepath, encoding);
res.json(JSON.parse(file));
});
Then in Angular, you'll have something like
http.get('/myfile').subscribe( (data) => { console.log("The data is: ", data) });
ADDED
The example I provided above was just the basics to answer your question. Ideally, in production for file paths, you should the Node path library which 'knows' how to behave in different environments and file systems.
Is it possible to convert a nodejs API server into a node module, which can be used for other projects without making much code changes?
Details: There are several API's(get, post, put) in the node js server. So if I use this server as a node module inside another node server, I must be able to access the API's in the node modules directly from the client. Is this possible? If yes, how?
I am required to do a POC on this for a client requirement and so far did not find it possible. Can you please help? I am relatively new to node js development
main script
const express = require('express');
const app = express()
/*
use some middlewares
*/
require('my-module')(app)
const server = http.createServer(app).listen(process.env.PORT);
module.exports = app;
module
module.exports = (app) =>{
app.get('/',(req,res) =>{
res.send('hi im a diffrent module;')
}
}
I'm working through designing my first webapp, I've already written a significant portion of the frontend and now I want to make a very simple backend to begin implementing some of the functionality. I've spent the last few days learning as much as I can about effective backend development and other various things, but I've run into a huge problem. I fundamentally don't understand how to attach my front end and my backend (which I want to use nodejs for).
All I want is to use my browser to go to localhost:8080 and automatically see the html document with my frontend then within my frontend code have the app communicate with the server (to get json info or instruct the server to add things to a database or things like that).
Once you have installed node in your system.
Folder structure:
Keep your files in public folder inside app folder
Navigate to your application folder in Terminal or Command Prompt:
Then create a file as package.json and keep following code in it:
{
"name" : "YourAppName",
"version" : "0.0.1",
"description" : "App description",
"dependencies" : {
"mime" : "~1.2.7"
}
}
then come back to terminal and run npm install
Then create a file as server.js and keep following code in it:
var http = require("http");
var fs = require("fs");
var path = require("path");
var mime = require("mime");
var cache = {};
function send404(responce){
responce.writeHead(404,{"content-type":"text/plain"});
responce.write("Error 404: resourse not found");
responce.end()
}
function sendFile(responce,filePath,fileContents){
responce.writeHead(200,{"content-type": mime.lookup(path.basename(filePath))});
responce.end(fileContents);
}
function serveStatic(responce,cache,abspath){
if(cache[abspath]){
sendFile(responce,abspath,cache[abspath]);
}else{
fs.exists(abspath,function(exists){
if(exists){
fs.readFile(abspath,function(err,data){
if(err){
send404(responce);
}else{
cache[abspath] = data;
sendFile(responce,abspath,data);
}
})
}else{
send404(responce)
}
})
}
}
var server = http.createServer(function(request,responce){
var filePath = false;
if(request.url == '/'){
filePath = 'public/index.html';
}else{
filePath = 'public'+request.url;
}
var abspath = './'+filePath;
serveStatic(responce,cache,abspath);
})
server.listen(8080,function(){
console.log("server running on 3000");
})
** This code is to help you get started with node js, for better understanding go to node documentation. Read about the mime module too, it is being used here.
You can use free cloud services such as Parse.com. this js sdk
You can use Grunt and using Connect plugin, create a simple server, sufficient for developing pure JS web applications.
Using Grunt basically requires 2 files
package.json
Gruntfile.js
package.json defines the dependencies required by Grunt to run. In your case it would include
grunt
grunt-contrib-connect (The plugin for setting up a server)`
It may also include additional dependencies based on your requirements.
Gruntfile.js defines the configuration for dependencies. In your case how the server should be setup. If you use plugins other that grunt-contrib-connect you should configure them too.
Reference:
Grunt: The JavaScript Task Runner
I am currently attempting to use Parse Web Hosting to setup a website for my iOS application. I am attempting to show a PDF file in the web browser located within my website directory. I am using express and heres whats going on so far
var express = require('express');
var app = express();
var fs = require('fs');
// Global app configuration section
app.set('views', 'cloud/views'); // Specify the folder to find templates
app.set('view engine', 'ejs'); // Set the template engine
app.use(express.bodyParser()); // Middleware for reading request body
app.get('/terms', function(request, response){
fs.readFile("/public/terms_conditions_hotspot.pdf", function (err,data){
response.contentType("application/pdf");
response.render(data);
});
});
app.listen();
So when I navigate to mysite.parseapp.com/terms, I get a 500 error.
But to make sure everything is setup correctly, I used Parse's boilerplate code to render a hello message when you navigate to mysite.parseapp.com/hello.
app.get('/hello', function(request, response) {
response.render('hello', { message: 'Congrats, you just set up your app!' });
});
This seems to work fine. Anyone know what the issue is?
My goal is migrating my Django Web app to using Parse Web Hosting instead mainly because Parse supports SSL and supplies free certs, which makes building this application cheaper (free). Although, my Django Web App's purpose is to deal with Stripe Connect redirects and used oAuth2, which may be problematic with the migration, seeing as Parse may not support certain modules or whatever. I just feel Parse is very limited with their services but I am anxious to see what I can do with it.
EDIT
So I ran console.log(error) and it returned:
Object [object Object] has no method 'readFile'
readFile is definitely a method that fs ('filesystem') contains. So maybe the module 'fs' in Parse isn't up to date or refers to a different module?
What the deuce?
Parse doesn't appear to use NodeJS (fs is a Node module) even though they offer Express.
See: https://www.parse.com/questions/loading-nodejs-packages-to-cloud-code