Saturday, 27 May 2017

How to access website content from onother server with express or http

How to access website content from another server with Express or HTTP

I have a website that holds all data like template website for example

and I have 3 more websites that get access this website template content HTML CSS everything inside website 2 3 and 4 the only defriend is the route like

mysite.com/template1/user1/index.html

mysite.com/template1/user2/index.html

mysite.com/template1/user3/index.html

I want to have inside website **(n)* only code that gets the HTML CSS and js content from the template server the master how I can do that?.

In PHP is something like

$url = $GET(www.masterserve.com/template1/ + user1 ) echo $url

Any example that I can do the same with node.js and express

// Get dependencies

const express = require('express');
const path = require('path');
const http = require('http');
const bodyParser = require('body-parser');

// Get our API routes
const api = require('./server/routes/api');

const app = express();

// Parsers for POST data
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Point static path to dist
app.use(express.static(path.join(__dirname, 'dist'))); <-- idont want static 
file only a URL from the master server

// Set our api routes
app.use('/api', api);

// Catch all other routes and return the index file
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});

/**
 * Get port from environment and store in Express.
 */
const port = process.env.PORT || '3000';
app.set('port', port);

/**
 * Create HTTP server.
 */
const server = http.createServer(app);

/**
 * Listen on provided port, on all network interfaces.
 */
server.listen(port, () => console.log(`API running on localhost:${port}`));



via George

Restart the process after uncaughtException in Express Js Server

I have express js server and i have handle the uncaughtException with the below code.

process.on('uncaughtException', function (error) {
     console.log(error.stack);
});

Once if uncaught exception throws it will show the error and below error message will be showing infinitely instead of restart the process. this issue will be exist in the forever start as well. below is the error after uncaught exception

[5]: Error: bind EACCES undefined
    at Object.exports._errnoException (util.js:1018:11)
    at exports._exceptionWithHostPort (util.js:1041:20)
    at cb (net.js:1323:16)
    at rr (cluster.js:625:14)
    at Worker.<anonymous> (cluster.js:594:9)
    at process.<anonymous> (cluster.js:765:8)
    at emitTwo (events.js:111:20)
    at process.emit (events.js:191:7)
    at process.nextTick (internal/child_process.js:753:12)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickDomainCallback (internal/process/next_tick.js:128:9)

This will be print continuously on the console after exception throws. please help me to restart the process after uncaught exception throws.



via sameera danthanarayana

Sending request to proxy server (Connecting front-end to back-end)

I'm trying to fetch JSON from darksky api (weather api) and according to its api, it is suggested to use a proxy server. I want to implement this using a nodejs proxy server demonstrated here: https://gist.github.com/davemo/4027855. If I already have the user's lat&long coordinates, how do I pass this to the nodejs server on the backend?



via Owen Chak

Node JS Event emitter not working if we first emit and then we listen

var events=require('events').EventEmitter;
var eventEmitter = new events();


eventEmitter.on('hello', function()
{ 
  console.log('Hey !!');
});

eventEmitter.emit('hello');

now if i first emit and then listen it will not print console.Help me to find the reason.



via john33

What is a better NoSql embedded db for Node.js?

I want to create a Node application that contains embedded file for DB. The DB should is NoSql Db.

i try use NoSql of Total.js, but it haven't a good documentation and example.

What is a stable e supported alternative for NoSql Embedded Db for Node?



via Pasalino

Multer returning File instead of an array

Im trying to upload multiple files to a nodeJS using the multer module. Reading the docs and req.files is suppose to be an array but I am getting an object with the field name as the key and a File object as the value.

Previously I had this with with angular2 but after switching over to react Im now having these issues. I am using the native fetch library which might make a difference but I don't think so since the request looks proper.

I have tried npm installing multer and event cloning multer from github into the node_modules directory

I am using Node v7.2, multer v1.2 with react on the frontend with native fetch to make the request.

Thanks


Node route:

const upload = multer({ dest: config.uploads.tempDir })
...
this.app.get('/uploads/:type/:filename', upload.fields([{ name: 'files[]', maxCount: 10 }]), this.display.bind(this));

The form data:

content-type:multipart/form-data; boundary=----WebKitFormBoundaryuWi9tvnulMlxRl1m

------WebKitFormBoundaryuWi9tvnulMlxRl1m

Content-Disposition: form-data; name="files"; filename="0fR0RmH.jpg"
Content-Type: image/jpeg

------WebKitFormBoundaryuWi9tvnulMlxRl1m
Content-Disposition: form-data; name="files"; filename="1d41a1d957c241d38a1f0782698710b2.jpeg"
Content-Type: image/jpeg

------WebKitFormBoundaryuWi9tvnulMlxRl1m--

req.files output

{ files: 
       File {
         domain: null,
         _events: {},
         _eventsCount: 0,
         _maxListeners: undefined,
         size: 713505,
         path: '/var/folders/85/dsxc639j6dg5yc6ljhy_vmhm0000gn/T/upload_8a839d16dc74cfd1709bdd78699b05c8',
         name: '1d41a1d957c241d38a1f0782698710b2.jpeg',
         type: 'image/jpeg',
         hash: null,
         lastModifiedDate: 2017-05-27T16:20:24.665Z,
         _writeStream: 
          WriteStream {
            _writableState: [Object],
            writable: false,
            domain: null,
            _events: {},
            _eventsCount: 0,
            _maxListeners: undefined,
            path: '/var/folders/85/dsxc639j6dg5yc6ljhy_vmhm0000gn/T/upload_8a839d16dc74cfd1709bdd78699b05c8',
            fd: null,
            flags: 'w',
            mode: 438,
            start: undefined,
            autoClose: true,
            pos: undefined,
            bytesWritten: 713505,
            closed: true } } }


The form:

<input 
    ref="fileUpload"
    name="files"
    multiple
    type="file"
    onChange={() => this.props.onChange(this.refs.fileUpload) }


via locrizak

Sending GET request from arduino using esp8266 wifi module to a nodejs server

I'm trying to send a GET request to an nodejs server (using express) from arduino mega using the wifi module esp8266 with the AT-Commands.

It seems the server doesn't receive nothing even if in the arduino serial monitor I can read "SEND OK" when the server is running.

The same command sent from arduino to an flask server works. With the Chrome browser the I have no problems, both nodejs server and flask receive the request.

I have spent a lot of days finding a solution for this problem, I don't understand where I am wrong.

Arduino code for sending request:

void sendGetRequest(String ip, int port, String buttonId) {
String command = "AT+CIPSTART=0,\"TCP\",";
command += "\"";
command += ip;
command += "\",";
command += port;
command += "\r\n";

sendData(command, 1000, DEBUG);
sendData("AT+CIPSEND=0,15\r\n", 1000, DEBUG);

String request = "GET /b1";
sendData(request, 1000, DEBUG);
sendData(" \r\n", 1000, DEBUG);
sendData(" \r\n", 1000, DEBUG);
sendData(" \r\n", 1000, DEBUG);

//sendData("AT+CIPCLOSE=4\r\n", 1000, DEBUG);
}

String sendData(String command, const int timeout, boolean debug) {
  String response = "";

  esp8266.print(command); // send the read character to the esp8266

  long int time = millis();

  while ((time+timeout) > millis()) {
    while (esp8266.available()) {

      // the esp has data so display its output to the serial window 
      char c = esp8266.read(); // read the next character.
      response+=c;
    } 
  }

  if (debug) {
    Serial.print(response);
  }

  return response;
}

NodeJs express endpoint:

var http = require('http');

//Server port
var port = 6882;

//Web server
var app = express();
var server = http.createServer(app);
server.listen(port, "0.0.0.0");

app.get('/b1', function (req, res) {
    console.log("Button pressed!" ); 
    res.send("Hello");
});

Flask simple server that works:

from flask import Flask
app = Flask(__name__)

@app.route("/b1", methods=["GET"])
def hello():
    return "Hello World!"

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)

Thanks for your help, and sorry for my bad english.



via Cosimo Lovascio