Posts

Showing posts with the label express

Authentification in just one file with Sequelize

Authentification in just one file with Sequelize I am trying to use Sequelize, but I don't know how to figure out that : I want to connect only one time in the start.js, and not in each file. This is my start.js : const Sequelize = require("sequelize"); // import environmental variables from our variables.env file require("dotenv").config({ path: "variables.env" }); // Connect to our Database const sequelize = new Sequelize( process.env.DATABASE_NAME, process.env.DATABASE_USER, process.env.DATABASE_PASSWORD, { host: process.env.DATABASE_HOST, dialect: "postgres", operatorsAliases: false, pool: { max: 5, min: 0, acquire: 30000, idle: 10000 } } ); // Try to authenticate to our databse sequelize .authenticate() .then(() => { console.log("🗄 Database connection successful !"); }) .catch(err => { console.error("🗄 Database connection error...", err); ...

Express launching Angular application

Express launching Angular application I have an express server setup online which loads multiple ports and those ports are setup on subdomains for example. port 9000 loads the main domain.com port 8000 loads the main application at "app.domain.com" port 1000 loads "signup.domain.com" and the build version of the app is on port 8500 "build.domain.com". The application is an Angular application however when I go to load the Angular app it loads on port 4200 or it says 8500 is in use. So currently I am loading that in express like so: // Build Application - In Development var appbuild = express(); appbuild.get('/', function (req, res){ res.sendFile('/app/build/myapp/src/index.html', { root: '.' }) }); var port = 8500; appbuild.listen(port); console.log('Build App Listening on port', port); So my question is in Express how can I instead of writing sendfile command make it launch the angular app in...

Axios looping promisses and update previous axios response data

Axios looping promisses and update previous axios response data How I can wait for all promises to be resolve in order to update the response.data of the first ajax call? (example using swapi.co api) A simple express .get wrapper. Each /starship list the pilots resource (see comment inside). I want to have full pilots data in my wrapper /api/starships. app.get('/api/starships/', function(req, res){ axios.get('https://swapi.co/api/starships') .then(function(response){ // res.setHeader('Cache-Control', 'no-control'); // pilots: [ // "https://swapi.co/api/people/13/", // "https://swapi.co/api/people/14/", // "https://swapi.co/api/people/25/", // "https://swapi.co/api/people/31/" // ], response.data.results.forEach(function(starship, i){ if (starship.pilots) { var promises = ; var fullpillots = ; starship.pilots.forEach(function(pilot_inf...

res.download function is not working in express.js

res.download function is not working in express.js I want to download a file in node.js using express.js framework according to the get request url. I didn't get an error in this code, but the file is not downloaded, it shows success message. Kindly look at following code, can anyone solve this issue? var express=require("express"); var bodyparser=require("body-parser"); var app=express(); var path=require("path"); app.get("/download/:folder/:file(*)",function(req,res) { var folder=req.params.folder; var filename=req.params.file; var downloadlocation=path.join(__dirname,folder,filename); console.log(downloadlocation); res.download(downloadlocation,function(err,success) { if(err) { console.log("download failed try again"); } else { console.log("download successfully"); } }); }); app.listen(8086,function() { console.log("serv...

For() loop go back at begining after few iterations

For() loop go back at begining after few iterations I have a very basic for(int i=0; i<array.length; i++) loop in an ExpressJs application. It iterates to access an array elements, do an http request, wait for the answer (with await), than save the results in a mongodb database. After a few iterations (3 or 4 elements) i can see in my logs that the i variable go back to 0 and it seems that the loop begins from 0 again; or my array have more than 100 elements. for(int i=0; i<array.length; i++) Desired behaviour : iterate on all elements, only one time inside my loop, from element 0 to array.length (basicaly i'm looking for normal behaviour of for() loop) Why?? Complete code : for(var i =0; i < stockList.length; i++){ var urlapi = someURL; let A = await getStock(urlapi); var symbolOfreturn = A.data["Meta Data"]["2. Symbol"]; var lastClose = A.data["Time Series (Daily)"]["2018-06-29"]["4. close"]; var openToday ...

Unexpected end of json input in Node.js

Unexpected end of json input in Node.js I have Json data which I receive it as post data in my node.js server. But the problem is, its not able to parse the string I sent.Here is my node.js server code. res.header("Access-Control-Allow-Origin", "*"); req.on('data',function(data) { var done=false; console.log(data); var schema; schema=JSON.parse(data); } Here I get the error when I parse the json data(data). undefined:776 SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) at IncomingMessage.<anonymous> (/Users/as6/Documents/test/server.js:206:17) at emitOne (events.js:115:13) at IncomingMessage.emit (events.js:210:7) at IncomingMessage.Readable.read (_stream_readable.js:462:10) at flow (_stream_readable.js:833:34) at resume_ (_stream_readable.js:815:3) at _combinedTickCallback (internal/process/next_tick.js:102:11) at process._tickCallback (internal/process/next_tick.js:...

Retrieving User Collection from API / MongoDB but exclude Password Field?

Retrieving User Collection from API / MongoDB but exclude Password Field? I am constructing an api which retrieves articles. I also have users in my database, and would like to have one endpoint which returns the user. /api/users/:userid . This returns something along these lines: /api/users/:userid { "articles": , //array w. references to articles the user has written "_id": "5b1321321bcda0e3364251d7e4a", "email": "user@email.com", "password": "$2a$1231241gi14k41k42bk12bh3k127iP/k1LAqwPdbgF/bXXpRia", "__v": 0 } -- However, I am not sure whether it's a good idea to return the (encrypted) password in the API. Can I somehow exclude this field, or would you recommend to store emails + user_ids in a separate collection on mongodb, or how are things like this usually handled? 2 Answers 2 you can use Project Fields to Retu...

NodeJS Auto-Update Dropdown menu based on MySQL queries

NodeJS Auto-Update Dropdown menu based on MySQL queries This is my first project working with Express & NodeJS so please bear with me, as I a a total newbie to JavaScript. I am currently trying to figure out how to create a dropdown menu that changes its values based on the options "pais", "titulacion" and "destino" selected from this DB (outgoing): +--------+-----------+------------+-----------+------------+----+ | nombre | apellidos | destino | pais | titulacion | id | +--------+-----------+------------+-----------+------------+----+ | John | Martinez | UPMC | Francia | GIB | 1 | | Marta | López | HEC | Francia | GITST | 2 | | Amadeo | Perez | Linköping | Finlandia | GITST | 3 | +--------+-----------+------------+-----------+------------+----+ I want to make it so that if I select "Francia" on the dropdown list, the other dropdown list for "destino" will only show those opt...