• Как сделать отправку сообщений Websocket конкретному клиенту в Go (с использованием Gorilla)+ сохранение сообщений в бд?

    @Abcdefgk
    Собственно, я для того сюда заглядываю, чтобы прочитать какую-нибудь проблему - и её порешать.
    Я сделал "приватный чат" - ну типа, 1+1, с восстановлением диалога при возвращении и т.д. - причём, в двух базах данных - MongoDB и PostgresQL. В обеих это делается запросто.
    Но тебе я этого не расскажу.
    (разлогиниваюсь)
    Ответ написан
    Комментировать
  • Как использовать stream вместе с express?

    @Abcdefgk
    stream.pipe(res);
    Ответ написан
    Комментировать
  • Как отличать клиентов на websocket сервере в nodejs?

    @Abcdefgk
    Ну-у-у... надо обратиться к матчасти. Понятный учебный пример тут ->
    Ответ написан
  • Почему не удаётся авторизоваться?

    @Abcdefgk
    Вообще, Axios - довольно забавный тип, в нем можно устанавливать "заголовки по умолчанию".
    И как не странно, это работает и на сервере.
    Вот такой, допустим, файл server.js
    const path = require('path');
    const express = require('express');           // For web server
    const bodyParser = require('body-parser');    // Receive JSON format
    const querystring = require('querystring');
    
    // Set up Express web server
    var app = express();
    app.use(bodyParser.json());
    // this line say of server, that we run server.js he open html file from public directory
    app.use(express.static(path.join(__dirname, 'public'))); // it was static(__ + 'public or www')
    
    // let's importing config.js file where are the configuration for dotenv/env and credentials_id/secret/url/PORT and scopes
    const config = require('./config');
    
    const PORT = config.credentials.PORT; // import from bim start.js
    const scopes = 'data:read data:write data:create bucket:create bucket:read';
    
    var indRouter = require('./routes/indRouter');
    indRouter(app);
    
    app.use((err, req, res, next) => {
      console.error(err);
      res.status(err.statusCode).json(err);
    });
    
    // This is for web server to start listening to port 3000
    app.listen(PORT, () => { 
      if (process.env.FORGE_CLIENT_ID == null || process.env.FORGE_CLIENT_SECRET == null) {
        console.log('*****************\nWARNING: Client ID & Client Secret not defined as environment variables.\n*****************');
      }
      console.log(`Server listening on port ${PORT}`);
    });

    В папке routes лежить вот такой файл indRouter.js
    var oauth = require('./oauth');
    var bucketCreate = require('./bucketCreate');
    var Axios = require('axios');
    var publ = require('./publ');
    var detail = require('./detail');
    
    module.exports = function(app) {
    	
    	app.get('/api/forge/oauth', function (req, res) {
    		oauth()
    			.then(function (response) {
    				// Success
    				var access_token = response.data.access_token;
    				Axios.defaults.headers.common['Authorization'] = 'Bearer ' + access_token;
    				//console.log(response);
    				res.redirect('/api/forge/datamanagement/bucket/create');
          })
    			.catch(function (error) {
    				// Failed
    				console.log(error);
    				res.send('Failed to authenticate');
    			});
    	});
    	
    	app.get('/api/forge/datamanagement/bucket/create', function (req, res) {
    		bucketCreate()
    			.then(function (response) {
    				// Success
    				//console.log(response);
    				res.redirect('/api/forge/datamanagement/bucket/detail');
          })
    			.catch(function (error) {
    				if (error.response && error.response.status == 409) {
    						console.log('Bucket already exists, skip creation.');
    						res.redirect('/api/forge/datamanagement/bucket/detail');
    				}
    				// Failed
    				console.log(error);
    				res.send('Failed to create a new bucket');
    			});
    	});
    	
    	app.get('/api/forge/oauth/public', function (req, res) {
        // Limit public token to Viewer read only
        publ()
    			.then(function (response) {
    				// Success
    				//console.log(response);
    				res.json({ access_token: response.data.access_token, expires_in: response.data.expires_in });
    			})
    			.catch(function (error) {
    				// Failed
    				console.log(error);
    				res.status(500).json(error);
    			});
    	});
    	
    	app.get('/api/forge/datamanagement/bucket/detail', function (req, res) {
    		detail()
    			.then(function (response) {
    				// Success
    				console.log(response);
    				res.redirect('/upload.html');
          })
          .catch(function (error) {
    				// Failed
    				console.log(error);
    				res.send('Failed to verify the new bucket');
          });
    	});
    	
    };

    И рядом с ним лежат файлы
    oauth.js
    const Axios = require('axios');
    const querystring = require('querystring');
    
    const config = require('../config');
    
    module.exports = function() {
      return Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: querystring.stringify({
          client_id: config.credentials.client_id,
          client_secret: config.credentials.client_secret,
          grant_type: 'client_credentials',
          scope: config.scopes.internal
        })
      });
    };

    bucketCreate.js
    const Axios = require('axios');
    const config = require('../config');
    
    // Prefix with your ID so the bucket key is unique across all buckets on all other accounts
    const bucketKey = config.credentials.client_id.toLowerCase() + '_my_first_full_viewer_bucket';
    const policyKey = 'transient'; // Expires in 24hr
    
      // Create an application shared bucket using access token from previous route
      // We will use this bucket for storing all files in this tutorial
    
    module.exports = function() {
      return Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/oss/v2/buckets',
        headers: {
          'content-type': 'application/json',
          //Authorization: 'Bearer ' + access_token
        },
        data: JSON.stringify({
          'bucketKey': bucketKey,
          'policyKey': policyKey
        })
      });
    };

    publ.js
    const Axios = require('axios');
    const querystring = require('querystring');
    const config = require('../config');
    
    module.exports = function() {
    	return Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: querystring.stringify({
    			client_id: config.credentials.client_id,
    			client_secret: config.credentials.client_secret,
    			grant_type: 'client_credentials',
    			scope: 'viewables:read'
        })
      });
    };

    detail.js
    var Axios = require('axios');
    const config = require('../config');
    
    // Prefix with your ID so the bucket key is unique across all buckets on all other accounts
    const bucketKey = config.credentials.client_id.toLowerCase() + '_my_first_full_viewer_bucket';
    
    module.exports = function() {
    	return Axios({
    		method: 'GET',
    		url: 'https://developer.api.autodesk.com/oss/v2/buckets/' + encodeURIComponent(bucketKey) + '/details',
    		//headers: {
    				//Authorization: 'Bearer ' + access_token
    		//}
      });
    };

    В первом обработчике (файл indRouter.js) установлен заголовок по умолчанию Authorization с токеном
    и больше его нигде писать не надо - он уже во всех запросах от Axios есть.
    Ответ написан
    3 комментария
  • Как передать значение промиса из одного файла в другой?

    @Abcdefgk
    server.js
    const path = require('path');
    const express = require('express');           // For web server
    const Axios = require('axios');               // A Promised base http client
    const bodyParser = require('body-parser');    // Receive JSON format
    const querystring = require('querystring');
    
    // Set up Express web server
    let app = express();
    app.use(bodyParser.json());
    // this line say of server, that we run server.js he open html file from public directory
    app.use(express.static(path.join(__dirname, 'public'))); // it was static(__ + 'public or www')
    
    // let's importing config.js file where are the configuration for dotenv/env and credentials_id/secret/url/PORT and scopes
    const config = require('./config');
    
    const PORT = config.credentials.PORT; // import from bim start.js
    const scopes = 'data:read data:write data:create bucket:create bucket:read';
    
    
    var oauth = require('./routes/oauth');
    var bucketCreate = require('./routes/bucketCreate');
    
    app.get('/api/forge/oauth', function(req, res) {
      oauth()
    		.then(function (response) {
    				// Success
    				// let's save token into the varible access_token
    				// Then, the app is routed to, which creates a shared bucket for our app.	
    				var access_token = response.data.access_token;
    				
    				bucketCreate(access_token)
    					.then(function (response) {
    						// Success
    						console.log(response);
    						res.redirect('/api/forge/datamanagement/bucket/detail');
    					})
    					.catch(function (error) {
    						if (error.response && error.response.status == 409) {
    							console.log('Bucket already exists, skip creation.');
    							res.redirect('/api/forge/datamanagement/bucket/detail');
    						}
    						// Failed
    						console.log(error);
    						res.send('Failed to create a new bucket');
    					});
    			})
          .catch(function (error) {
            // Failed
            console.error(error);
            res.send('Failed to authenticate');
          });
        });
    		
    		
    
    app.use((err, req, res, next) => {
      console.error(err);
      res.status(err.statusCode).json(err);
    });
    
    // This is for web server to start listening to port 3000
    app.listen(PORT, () => { 
      if (process.env.FORGE_CLIENT_ID == null || process.env.FORGE_CLIENT_SECRET == null) {
        console.log('*****************\nWARNING: Client ID & Client Secret not defined as environment variables.\n*****************');
      }
      console.log(`Server listening on port ${PORT}`);
    });

    oauth.js
    /*
     * Authentication
     */
    const Axios = require('axios');
    const querystring = require('querystring');        
    
    const config = require('../config');
    
    module.exports = function() {
      return Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: querystring.stringify({
          client_id: config.credentials.client_id,
          client_secret: config.credentials.client_secret,
          grant_type: 'client_credentials',
          scope: config.scopes.internal
        })
      });
    };

    backetCreate.js
    /*
     * Bucket Creation
     */
    const Axios = require('axios');
    const config = require('../config');
    
    // Prefix with your ID so the bucket key is unique across all buckets on all other accounts
    const bucketKey = config.credentials.client_id.toLowerCase() + '_my_first_full_viewer_bucket';
    const policyKey = 'transient'; // Expires in 24hr
    
      // Create an application shared bucket using access token from previous route
      // We will use this bucket for storing all files in this tutorial
    
    module.exports = function(access_token) {
    												console.log('!!!!!!!!!!!!! ' + access_token);
      return Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/oss/v2/buckets',
        headers: {
          'content-type': 'application/json',
          Authorization: 'Bearer ' + access_token
        },
        data: JSON.stringify({
          'bucketKey': bucketKey,
          'policyKey': policyKey
        })
      });
    };
    Ответ написан
    Комментировать
  • Как передать значение promise из одного файла в другую?

    @Abcdefgk
    Принкцип такой.
    Пишешь модуль oauth.js, который выглядит так:
    const Axios = require('axios');             
    const querystring = require('querystring');
    
    var FORGE_CLIENT_ID = 'myId';
    var FORGE_CLIENT_SECRET = 'mySecret';
    const scopes = 'data:read data:write data:create bucket:create bucket:read';
    
    module.exports = function() {
      return Axios({
        method: 'POST',
        url: 'https://developer.api.autodesk.com/authentication/v1/authenticate',
        headers: {
          'content-type': 'application/x-www-form-urlencoded',
        },
        data: querystring.stringify({
          client_id: FORGE_CLIENT_ID,
          client_secret: FORGE_CLIENT_SECRET,
          grant_type: 'client_credentials',
          scope: scopes
        })
      });
    };

    И в том месте, где он нужен, его вызываешь с продолжением
    require('./oauth')
      .then(function (response) {
        access_token = response.data.access_token;
      })
      .catch(...

    Сам принкцип. А что должно быть за продолжение, где, какой-то редирект в then - куда? Это у тебя ничего не понятно. Тут проблема в самой общей конструкции (а не в синтаксисе-шминтаксисе, конечно).
    Ответ написан
  • Как скрыть данные SQL в node JS?

    @Abcdefgk
    Думаю, самое время приступить к изучению Node.js сначала.
    Ответ написан
    Комментировать
  • Как заставить работать прокси socket.io через nginx на Ubuntu?

    @Abcdefgk
    Короче, я тут поковырялся. И у меня получилось за Нгинксом его заставить работать, но только - создавая "пространство имён" принудительно.
    На клиенте запрос на подключение выглядит так
    var socket = io('http://localhost/sock');
    на сервере так
    var io = require('socket.io')(3001); // спицально ему другой порт прикрутил, для "чистоты эксперимента"
    var chat = io.of('/sock');
    chat.on('connection', socket => { ...

    и дальше везде, где был io в коде - заменить на переменную chat - типа chat.to(socket.id).emit... и т.д. (хотя, видимо, можно было и просто - io переопределить: io = io.of('/sock');).
    И наконец, Nginx его перенаправляет так
    location /sock {
    						proxy_set_header Upgrade $http_upgrade;
    						proxy_set_header Connection "upgrade";
    						proxy_http_version 1.1;
    						proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    						proxy_set_header Host $host;
    						proxy_pass http://127.0.0.1:3001/sock;
    				}

    Так всё зафурычило.
    Ответ написан
    2 комментария
  • Как сделать из string number?

    @Abcdefgk
    Экзотический вариант
    var n = +'222';
    console.log(typeof n); // number
    Ответ написан
    Комментировать
  • WebRTC How to get android stream?

    @Abcdefgk
    Комментировать
  • Как подключить базу данных SQL server к приложению на node js?

    @Abcdefgk
    Тут же, как я понимаю, есть два вопроса.
    1. А у виртуальной машины включена поддержка второго адаптера (который не NAT) - "виртуальный хостинг". Патамушта без этого она-то может выходить вовне (посредством NAT, который всегда включен по умолчанию), а в неё-то - извне - достучаться нельзя.
    2. А у Windows XP IP-адрес руками установлен (какой-нибудь 192.168.33.10), а так же маска подсети (какая-нибудь 255.255.255.0)
    Если это дело есть, то вот этот 192.168.33.10 и надо писать в конфиг подключения (заместо слова localhost).
    Ответ написан
  • Как клиент должен установить http Authorization: token при запросе на сервер?

    @Abcdefgk
    В реальной жизни JWT-авторизацию юзают в лендингах. Поэтому в них так любят axios для AJAX-запросов - в нём можно после получения токена добавить "заголовок по умолчанию", просто чтобы каждый раз при запросе не лазить за ним в Store (где его, конечно, тоже сохраняют).
    Ответ написан
    Комментировать
  • Можете посоветовать веб сервер?

    @Abcdefgk
    Дурдом.
    Правильные ответы не отмечены "ответами", а примитивные - отмечены.
    Очевидно же, что тут нужно заюзать Nginx.
    Ответ написан
    Комментировать
  • Как правильно сделать cache-control в get запрос приложения node.js?

    @Abcdefgk
    Ну это какбэ матчасть - cделать мидловер.
    Скопируй в "главный файл" перед роутами вот это
    app.use(function(req, res, next) {
      res.setHeader('Cache-Control', 'no-cache');
      next();
    });

    Всего делов.
    Ответ написан
  • MongoDB: копятся активные подключения, что делать?

    @Abcdefgk
    Реквайрить mongoose в этот файл (безо всяких выкрутасов) и написать mongoose.disconnect() в конце.
    Ответ написан
    Комментировать
  • Структура с полем, содержащим JSON-строку. Как из такой структуры получить правильный JSON?

    @Abcdefgk
    Надо на клиенте выкинуть эти слеши из строки да и всё - str.replace(/\\/g, '');
    "tickets": "[{"p": 90}, {"p": 90}]",
    Ответ написан
    Комментировать
  • Какие подходы используете для формирования шаблона с разными правами доступа?

    @Abcdefgk
    Вообще-то, стандартно "ключ" роли пользователя записывают в res.locals в обработчике запроса, а в самом шаблоне предусматривают варианты для разных ролей, которые - в зависимости от роли (прав доступа) - отдаются на генерацию на основе простой проверки типа if(key == 'Admin')...
    Собстно, это то же самое, что и res.render('index', {key : session.key}); , только "правильнее".
    Ответ написан
    3 комментария
  • Import в nodejs 10.11.0 - как заставить работать?

    @Abcdefgk
    А если такой неожиданный вариант.
    Написать, например, так
    var { app, BrowserWindow } = require('electron');
    Может сработать (но это не точно).
    Ответ написан
    Комментировать