Bolo
Bolo

Reputation: 45

Nodejs: Display POST data from another website

Im trying to figure it out for past 6 hours, but Im out of ideas..

What Im trying to accomplish:

I want to display a JSON data that looks like this

movie {title: " xxxxx", seed: "number", url: "zzzzzzzzz"}

I want to display it on my Node server(via jade), but what I accomplished till now is to send it from the website to my node server via POST request using this code:

My JS script

var http = new XMLHttpRequest();
var url = "http://localhost:8080/";
var params = arr; <------ My JSON data
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        console.log(http.responseText);
    }
}
http.send(params);

After using above code in my google chrome developer tools on the website I actually have that data, I receive the JSON array in my node, here is my node code:

My app.js node server

const http = require("http");
const express = require('express');
const app = express();
const myParser = require('body-parser');


app.set('views', __dirname + '/views')
app.set('view engine', 'jade')
app.use(express.static(__dirname + '/public'))
app.use(myParser.urlencoded({ extended: false }));
app.use(myParser.json())

var allowCrossDomain = function (req, res, next) {
  res.header('Access-Control-Allow-Origin', "*");
  res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
}

app.use(allowCrossDomain);

app.get('/', function (req, res, next) {
  res.render('index');
})

app.get('/tl', function (req, res, next) {
  res.render('tl');
})

app.post("/", function (req, res) {
  response = {
    first_name: req.body
  };

  console.log('SHOW ME BODY')
  console.log(req.body);

  res.send('You sent: this to Express');
});

app.listen(8080);

And this is what Im receiving in my node command prompt:

{ '[{"title":" SOME-MOVE-TITLE","seed":"NUMBER","url":"https://SOMEURLS.COM', etc. etc. etc.

And finally here is my layout.jade file

doctype
html
  head
    title Bolo Node Server
    link(rel="stylesheet", type="text/css", href="stylesheet/style.css")
  body
    header
      h1 My Site
      block content
    footer
      p Running on node with Express, Jade and Stylus

And index.jade

extend layout

block content
  p= 'Block content works'
  script.
    if req.body != undefined
      div(id='data')= req.body

I really run out of ideas on how to display the json array Im receiving...help me out please

Update

My index.jade

extend layout

block content
  p= 'Block content works'
  div(id='data')
    pre
      test= jsonString

My app.js looks now like this:

app.get('/', function (req, res, next) {
  res.render('index');
})

app.post("/", function (req, res) {
  // Get string representation
  var jsonString = JSON.stringify(req.body || {}); // use JSON.stringify(req.body || {}, null, 2) for formatted JSON
  console.log(jsonString);
  res.render('index', {test: jsonString});

  //res.send('You sent: this to Express');
});

I see the data in my node command prompt, but I dont see it on my local website http://localhost:8080/ the div(id='data') is showing me empty.. nothing, how do I get the jsonString there?? I want it to show me the data on my local website..

**

UPDATE

**

I ended up just putting the data into the sqlite3 database and then retrieving the data via GET request and finally putting it into my jade template. I thought I can go around and not use sqlite3 but I couldnt figure out how.

Upvotes: 2

Views: 911

Answers (4)

Bolo
Bolo

Reputation: 45

I ended up just putting the data into the sqlite3 database and then retrieving the data via GET request and finally putting it into my jade template. I thought I can go around and not use sqlite3 but I couldnt figure out how.

Here is the code

app.post("/", function (req, res) {
  var jsonString = JSON.stringify(req.body || {});
  db.serialize(function () {
    var stmt = db.prepare("INSERT INTO movies (id, title, seed, url) VALUES (?,?,?,?)");
    for (var i = 0; i < req.body.length; i++) {
      var d = new Date();
      var data = req.body;
      var n = d.toLocaleTimeString();
      stmt.run(i, req.body[i].title, req.body[i].seed, req.body[i].url);
    }
    stmt.finalize();
  });
  res.send('You sent: this to Express');
});

Retrieving the data from the database

app.get('/tl', function (req, res, next) {
  db.all('select * from movies', function (err, rows) {
    if (err)
      return next(err);
    var dataO = [];
    rows.forEach(function (row) {
      dataO.push(row);
    })
    res.render('tl', { dataO: dataO });
  })
})

Upvotes: 0

gtrenco
gtrenco

Reputation: 375

First you should parse your incoming data, as is application/x-www-form-urlencoded. You'll need to JSON.parse req.body first and encode your response as json too

app.post("/", function (req, res) {
  var  response = try { JSON.parse(req.body) } catch(e) { console.error('Invalid Data') };
  res.json(response || {});
});

You could also send your data as 'application/json' from you client JS and save receive a JSON directly to the req.body.

Hope it helps

UPDATE (if you want to append new data via async requests on the client)

In this post you can see the use of XmlHttpRequest with jquery $.ajax() which is basically the same concept of async requests after the DOM is rendered on your server.

Imagine the step 3 being your Jade rendered HTML

Upvotes: 0

Chirag Ravindra
Chirag Ravindra

Reputation: 4830

When you say that you want to display the json, if you just want to see the contents of the json you can use res.json.

app.post("/", function (req, res) {
  // Send back the request body if present or else, an empty object
  res.json(req.body || {});
});

If you want it to be displayed inside a template, you can get a string representation of the json using JSON.stringify(req.body) and render that in your template by passing it to it as a local variable.

app.post("/", function (req, res) {
  // Get string representation
  var jsonString = JSON.stringify(req.body || {}); // use JSON.stringify(req.body || {}, null, 2) for formatted JSON

  res.render('jsonView',{jsonString});
});

And in your template:

div(id='data')
  pre
    code = jsonString

Upvotes: 1

Sir Rubberduck
Sir Rubberduck

Reputation: 2252

You should pass the data in the template.

res.render('index', {data: 'data'});

And show it with:

data = data
    p #{data}

Upvotes: 0

Related Questions