Node Server receive XmlHttpRequest - json

I'm using the following code to send a session description (tiny JSON code - http://www.ietf.org/rfc/rfc2327.txt).
function sendMessage(message) {
var msgString = JSON.stringify(message);
console.log('C->S: ' + msgString);
path = '/message?r=67987409' + '&u=57188688';
var xhr = new XMLHttpRequest();
xhr.open('POST', path, true);
xhr.send(msgString);
}
I'm not sure how to go about retreiving the JSON on my Node.js server.

Here's a code that can handle POST request in node.js .
var http = require('http');
var server = http.createServer(function (request, response) {
if (request.method == 'POST') {
var body = '';
request.on('data', function (data) {
body += data;
});
request.on('end', function () {
var POST = JSON.parse(body);
// POST is the post data
});
}
});
server.listen(80);
Hope this can help you.

Related

XMLHttpRequest ERROR in QML Blackberry 10

I'm trying to get movie data for BlackBerry 10 apps.
I don't know where I'm making a mistake.
Please, can you help me?
Thank you all.
import bb.cascades 1.4
Page {
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var data = "{}";
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send(data);
}
}
You need to use the onreadystatechange EventHandler.
Also, you don't need to pass data when making a GET request.
I have removed the withCredentials line as it isn't needed in this example.
You can learn more on XMLHttpRequest here :
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
onCreationCompleted: {
sendRequest();
}
function sendRequest() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
var json = JSON.parse(xhr.responseText);
var results = json.results;
var count = results.length;
console.log("There are " + count + " results :");
json.results.forEach((value, index) =>
{
console.log(index + " - " + value.title);
});
}
};
xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
xhr.send();
}
Here's an example of using XMLHttpRequest I've made a long time ago :
https://github.com/RodgerLeblanc/Markup/blob/master/assets/main.qml

How to print external API on my server? (Take user ip address and show it on website)

I have just started using nodejs and koajs, and I would like to take the ip address from here: https://api.ipify.org?format=json and paste it on my site or set it as a header. Right now I have the following:
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
});
});
app.listen(8888);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
I know that I am probably doing something very wrong here but yea I am currently stuck because I have no idea how to take par.ip and assign it to this.body and set.
Would anyone be able to tell me how to achieve this or an alternative to the problem? Thanks in advance.
Assuming the response from api.ipify.org doesn't change.
var koa = require('koa');
var app = koa();
var http = require('https');
var a = http.get("https://api.ipify.org?format=json",function(res) {
var data = "";
res.on("data", function (chunk) {
data += chunk;
});
res.on('end', function() {
par = JSON.parse(data);
console.log(par.ip);
app.use(function *(){
this.response.set("userIp",par.ip);
this.body = "ipadress: "; //this doesn't see par.ip;
});
app.listen(8888);
});
});
Otherwise if the response from api.ipify.org constantly changes, you might to do the http request on every incoming request.

Retrive single data from json object in nodejs

i am new in nodejs . i tried the below code for retriving json object. but i can't retrive a single data from json object
My code is
function getData(){
var http = require('http');
var qs = require('querystring');
var str = '';
var options = {
host: '192.168.1.16',
port: 8080,
path: '/courseapi/view'
};
callback = function(response) {
response.on('data', function (chunk) {
str += chunk;
});
response.on('end', function () {
console.log(str);
console.log(str[0]._id);
});
}
var req = http.request(options, callback).end();
};
i tried this str[0]._id but it return undefined
Try:
response.on('end', function () {
str = JSON.parse(str);
console.log(str);
console.log(str[0]._id);
});

nodejs puts post data into new json

When I sending post request by this code:
var data = '{data: 1111}'; // = JSON.stringify(message);
console.log('NotifySplitter: ' + data);
var options = cfg.splitterOptions;
options.headers['Content-Length'] = Buffer.byteLength(data)
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log("body: " + chunk);
});
});
req.write(data);
req.end();
... and getting data by this code:
var express = require('express');
var app = express();
app.use(express.bodyParser());
app.post('/', function(request, response){
var query = request.body;
console.log(request.body);
response.end();
});
request.body contains:
{'{data: 1111}': ''}
instead expected {data: 1111}. Is it normal? How to get normal data without replacing external {} in origin data before post?
You have to set up an appropriate content-type. If you're sending json, add options.headers['Content-Type'] = 'application/json' to your request.
Also, {data: 1111} is not a JSON, it's JSON5. While it's better all around, it's not supported by default express.bodyParser(), so watch out for that.

How to make multipart form api requests with requestjs and nodejs?

Trying to interact with the phaxio api using multipart form data. As per the request.js docs for making a post request I do
var request = require('request');
var options = {
uri: 'https://api.phaxio.com/v1/send',
headers: {'content-length':'0'}
};
var r = request.post(options);
var form = r.form();
form.append('api_key', '1234');
form.append('api_secret', '1234');
form.append('to', '1234');
r.on('response', function(chunk){
console.log(chunk);
});
The response body I get from the r.on method is here http://pastie.org/private/wshbn9esendccrkoreeiow I'm unsure how I can see the api response body from the server after submitting the form data. Something like
{
"success": true,
"message": "Fax Sent!"
}
The method request.post() returns a readable stream. Just read the response:
var res = '';
r.on('data', function(data) {
res += data;
});
r.on('end', function() {
console.log(res);
});
You can also pipe the response to another writable stream:
var fs = require('fs');
var writable = fs.createWriteStream('/file');
r.pipe(writable);