Cannot read property 'swaggerUi' of undefined - javascript

Having a problem where the following code returns Cannot read property 'swaggerUi' of undefined each time I run node app.js. The code below is the entirety of app.js.
I have tried a bunch of different npm installs, computer restarts, and all of that. Nothing seems to change it.
var SwaggerExpress = require('swagger-express-mw');
var app = require('express')();
module.exports = app; // for testing
var config = {
appRoot: __dirname // required config
};
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 10010;
app.use(swaggerExpress.runner.swaggerTools.swaggerUi());
app.listen(port, function() {
console.log('Server running at http://127.0.0.1:' + port + '/');
});
if (swaggerExpress.runner.swagger.paths['/hiMom']) {
console.log('try this:\http://127.0.0.1:' + port + '/docs');
}
});

Here is a github sample link that might be be helpful
sample-swagger-for-nodejs.

SOLVED: I'm not sure what the problem was, but getting a fresh clone of the GitHub repo solved the problem.

Related

Error when sending a request to the Postman

So I am fairly new to the backend. Anyway, I want to create an API that I can use in the front-end, the error I am facing when I try to send a request to the localhost:5000/elements Postman is giving me Error: connect ECONNREFUSED 127.0.0.1:5000 if someone could help me it would be awesome. Thanks
var fs=require('fs');
var data=fs.readFileSync('books.json');
var elements=JSON.parse(data);
const express = require("express");
const app = express();
const cors=require('cors');
const Port = 5000
app.listen(process.env.Port, () => console.log("Server Start at " + Port));
app.use(express.static('public'));
app.use(cors());
app.get('/elements',alldata);
function alldata(request,response)
{
response.send(elements);
}
app.get('/elements/:element/',searchElement);
function searchElement(request,response)
{
var word=request.params.element;
word=word.charAt(0).toUpperCase()+word.slice(1).toLowerCase();
console.log(word);
console.log(elements[word]);
if(elements[word])
{
var reply=elements[word];
}
else
{
var reply={
status:"Not Found"
}
}
console.log(reply.boil);
response.send(reply);
}
This problem usually happens if you forget to run npm start.
Either way, I recommend moving the app.listen to the bottom of the code. It helps with readability, and it will mount all of code before running the Express server.
Your process.env.Port is also undefined. Change it to const port = process.env.Port || 5000 so you can get a fallback value. Change it also in the app.listen.
Then, define allData and searchElement so they are located before the app.get('/elements'). Finally, after you have done all of this, make sure that the request type in Postman is GET.
process.env.Port is unrelated to Port.
It's
app.listen(Port, () => console.log("Server Start at " + Port));

Why is the server response incorrect when the request is read correctly?

I'm on the Node.js repl, I created a new project folder and initialized the NPM, then I installed the Express package and wrote the following code into the js file:
const express = require('express');
const app = express();
app.listen(5000, function(){
console.log("server started on port 5000");
})
app.get("/", function(req, res){
res.send("Hi There! Welcome!")
})
app.get("/speak/:animalName", function(req,res){
var animalName = req.params.animalName;
var verso = "verso";
if (animalName = "pig"){
verso = "oink"
} else if (animalName = "dog"){
verso = "bau"
} else if (animalName = "cat"){
verso = "Miao"
}
console.log(req.params);
res.send("THE " + animalName + " says " + verso);
})
app.get("*", function (req, res){
res.send("Sorry, the page cannot be found")
})
When I open the js file with Nodemon the server starts correctly and when I type a specific pattern in the URL field the console.log returns me the req.params correctly (in the example below: for I typed "cat" the console returned { animalName: 'cat' }
Nonetheless, the response in the browser is not the correct one:
You're using a single = in your conditions. This always assigns the variable, instead of testing for equality. Use == or ===.

(crypto.js) TypeError: Data must be string or buffer

I am currently using crypto.js module to hash things. It was working for a while then I started getting this error:
Here is the foundation of my server:
process.stdout.write('\033c'); // Clear the console on startup
var
express = require("express"),
app = express(),
http = require("http").Server(app),
io = require("socket.io")(http),
path = require("path"),
colorworks = require("colorworks").create(),
fs = require("fs"),
crypto = require("crypto");
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
http.listen(443, function(){
// Create the http server so it can be accessed via 127.0.0.1:443 in a web browser.
console.log("NJ project webserver is running on port 443.");
// Notify the console that the server is up and running
});
app.use(express.static(__dirname + "/public"));
app.get("/", function(request, response){
response.sendFile(__dirname + "/public/index.html");
});
I am aware that these functions are creating the problem:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
The problem being, if these functions don't work (which they don't anymore), roughly 200 lines of code will go to waste.
This error is triggered by attempting to hash a variable that does not exist:
function md5(msg){
return crypto.createHash("md5").update(msg).digest("base64");
}
function sha256(msg) {
return crypto.createHash("sha256").update(msg).digest("base64");
}
md5(non_existent); // This variable does not exist.
What kind of data are you trying to hash ? Where does it come from ?
I would check the value of msg first then I would try :
crypto.createHash('md5').update(msg.toString()).digest('hex');
You could also use these packages instead:
https://www.npmjs.com/package/md5
https://www.npmjs.com/package/js-sha256

How do you use a Node.js variable on the client-side?

I'm relative new to NODEJS and I'm struggling with a basic problem, which is the correct use of global variables, I read a lot about it but it seems I can't make it work properly, I'll post some codes for a better view of the problem.
I have this simple js running as a server:
myapi.js
var http = require('http');
var express = require('express');
var app = express();
var exec = require('child_process').exec, child;
var fs = require('fs');
var jUptime;
var ipExp = require('./getDown');
var filesD = [];
var path = "/media/pi/01D16F03D7563070/movies";
app.use(express['static'](__dirname ));
exec("sudo /sbin/ifconfig eth0 | grep 'inet addr:' | cut -d: -f2 | awk '{print $1}'", function(error, stdout, stderr){
ip = stdout;
exports.ipAdd = ip;
console.log(ip);
});
app.get('/files', function(req, res) {
fs.readdir(path, function(err, files) {
if (err){
console.log("Non riesco a leggere i files");
}
filesD=files;
console.log(filesD);
});
res.status(200).send(filesD);
});
app.get('/up', function(req, res) {
child = exec("uptime -p", function(error, stdout, stderr){
jUptime = [{uptime: stdout}];
});
res.status(200).send(jUptime);
});
app.get('*', function(req, res) {
res.status(404).send('Richiesta non riconosciuta');
});
app.use(function(err, req, res, next) {
if (req.xhr) {
res.status(500).send('Qualcosa รจ andato storto');
} else {
next(err);
}
});
app.listen(3000);
console.log('Server attivo sulla porta 3000');
And then I have this JS used in a simple web page:
getDown.js
var ip = require('./myapi').ipAdd;
function gDownloads() {
var url;
var jqxhr;
var dat;
url = 'http://' + ip + '/files';
jqxhr = $.getJSON(url, function(dat) {
for(i=0; i<dat.length; i++){
$('#downLoad').append('<p>' + dat[i] + '</p>');
}
$('#bId').append(dat.length);
})
.done(function() {
console.log("OK");
})
.fail(function(data) {
console.log("Fallito: "+data);
})
};
The problem is that when I navigate to the html page that use getDown.js I get the following error on getDown.js
require is not defined
I need to pass the variable that contains the IP address in myapi.js to use it in getDown.js, I hope I explain myself good enough, thanks in advance.
require is global that exists in Node.js code, that is, on the javascript code executing in the server.
Your server will respond to the client and give it an HTML page to render. That HTML page could tell the browser to also request a javascript file from the server. When it receives that file, the client will execute it. The client does not have a require global (you can test it by opening up the console and typing require)
Using Browserify
Or you can write Node-style code, requiring your global like you're doing, but then run the code through browserify. This will create a new javascript bundle that can be executed by the client, so you should tell your html page to use that bundle instead of getDown.js.
Here is a basic example of doing using browserify like this.
module.js
function getIp() {
return 123456;
}
module.exports = {
getIp: getIp
};
main.js
var module = require('./module');
function getIp() {
var ip = module.getIp();
return ip;
};
console.log(getIp());
compile bundle
$ browserify main.js -o public/bundle.js
index.html
<script type="text/javascript" src="public/bundle.js"></script>
Global variable on the client
To use a global variable on the client which is known by the server, you can pass that variable to your rendering engine (possibly Jade if you're using Express) and have it interpolate that variable into a <script> tag which defines some globals. Leave a comment if that's the approach you'd prefer and I can add some more details.
Let me know if you have more questions!

Node.js. Error: module is not a function

i have a main file -- index.js:
var express = require('express');
var app = express();
var request = require('request');
var demo = require('demo');
// This app will only respond requests to the '/scrape' URL at port 3000.
app.get('/scrape', function (req, res) {
var url = "http://www.l.com";
request(url, function (error, response, html) { // two parameters: an URL and a callback
if (!error) {
demo(html);
}
});
});
var server = app.listen(3000, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
and my module is demo.js:
module.exports = function (html) {
....
return JSON.stringify(json);
}
The error is :
TypeError: demo is not a function
I am new to node.js, i would like to know why this didn't work. Maybe i dont understand the real principle of module?
Thank you for answer me first.
You're not exporting your module properly. It should be:
exports.demo = function ....
Try to include your demo module in index.js:
var demo = require('./demo.js');
For the other freshers who use module in node.js for the first time.
first, made a new module called the name of your module.js
Second, it is not necessary to do "
npm install demo --save", if you want, it is also okay.
Third, in the main js which u want to call this module, focus on the name and the path of the module, you should write var anyName = require('the name of your module');, if they are in the same directory, you should write like this: var anyName = require('./the name of your module');

Categories