Friday, 12 May 2017

NODE.JS: client http request to open specific page issue

I'm trying to make a http request and open a specific page in the browser. I've tried several packages such as npm opn, npm open, openurl but I can't get the desired objective. Here's what i'm trying:

server.js

var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var http = require('http');
var fs = require('fs');

var urlencodedParser = bodyParser.urlencoded({ extended: false })

app.use(express.static('public'));

app.get('/index.html', function (req, res) {
   res.sendFile( __dirname + "/" + "index.html" );
})

app.post('/process_post', urlencodedParser, function (req, res) {

   response = {
      fname:req.body.fname,
      surname:req.body.surname,
      age:req.body.age,
      phone:req.body.phone,
      city:req.body.phone,
      email:req.body.email,
      country:req.body.country,
      postal_code:req.body.postal_code,
      password:req.body.password
   };
   console.log(response);
   res.end(JSON.stringify(response));

   var exportJson= JSON.stringify(response);

   fs.writeFile("input.txt", exportJson, function(err) {
    if(err) {
        return console.log(err);
    }
});

}) 

var server = app.listen(8081, function () {
   var host = server.address().address
   var port = server.address().port

   console.log("Listening at http://%s:%s", host, port)

})

client.js

var http = require('http');
var opn=require('opn');

// Options to be used by request 
var options = {
   host: '127.0.0.1',
   port: '8081',
   path: '/index.html'  
};

//opn("https://google.pt");
 var callback = function(response){
   // Continuously update stream with data
   var body = '';
   response.on('data', function(data) {
      body += data;
   });

   response.on('end', function() {
      console.log(body);
   });
}
var req = http.request(options, callback);
//req=opn(options.path);
req.end();



via glassraven

No comments:

Post a Comment