AJAX Helper for NodeJS, instead of jQuery? - javascript

I just want to do something like $.get/post on a server side script. Is there a better way instead of including the whole jQuery? I prefer not to use the messy get xml http requests stuff manually either.

The equivalent to jquery.ajax in node.js is request
It sits on top of the node core http and makes things nicer to work with. Allowing for both callback and streaming requests.
examples:
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body) // Print the google web page.
}
})
request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png'))

require http. As found in their documentation you can make a request like the following:
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
There is a simple GET as well:
http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
You can also look into Express.js and request, there really are many options that you could use besides jquery.

Related

HTTPS handshake failure on IoT device

I am running buildroot and iotjs on an iot device and I'm trying to make a post request to login and get an auth token. But I'm unable to call the API at all because I run into an error that says
"API Failed, problem with request: handshake failed: domian"
The same API works given I use the http version. The server I'm trying to call is hosted on an AWS EC2 instance behind cloudflare.
The code (not exactly the same but similar) used to call the API:
var https = require('https');
var options = {
host: 'www.google.com',
port: 443,
path: '/upload',
method: 'POST'
};
var req = https.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Any help is appreciated thanks!

HTTP POST in Espruino for Microcontrollers

I recently got myself an esp8266-12e module and loaded the ESPRUINO.js firmware on it. I am trying execute a post request from the device, but the device always returns a 'no connection' error when trying to POST.
To troubleshoot I have ran a GET request to the same URL, and the request was successful, this means that internet is working on the device and communication with the intended server is possible.
I then moved on to see if there were errors in my HTTP POST code, I ran the same code in a node.js app and it successfully posted to the server.
Here is the code below, I removed the exact address of my server and my wifi/pass info.
var http = require("http");
var wifi = require("Wifi");
var sdata = {
deviceID: 'esp-12',
};
var options = {
hostname: 'immense-XXXXXX-XXXXX.herokuapp.com',
method: 'POST',
path:'/MXXXXXX',
headers: {
'Content-Type': 'application/json'
}
};
var req = http.request(options, function(res) {
console.log('Status: ' + res.statusCode);
console.log('Headers: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function(body) {
console.log('Body: ' + body);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
payload = JSON.stringify(sdata);
req.write(payload);
req.end();
terminal response from device after execution
problem with request: no connection
Here is the documentation for Espruino.js HTTP module.
https://www.espruino.com/Reference#http
Can any of the JS gurus see an issue with the request?
Turns out the http post request requires the 'content-length' header to function correctly.
Here is the working post request model for anyone who may need it. Note: Payload has already been formatted as a JSON object.
function postX(payload) {
var options = {
host: 'url',
port: '80',
path:'/ext',
method:'POST',
headers: { "Content-Type":"application/json", "Content-Length":payload.length }
};
var req = require("http").request(options, function(res) {
res.on('data', function(data) {
console.log("-->"+data);
});
res.on('close', function(data) {
console.log("==> Closed.");
ticksSinceConnect = 0;
});
});
req.end(payload);}

Upload file in node.js and POST multipart in spring boot

How send files uploaded in node.js (multipart) through http, something like this:
var options = {
host: url,
port: 8080,
path: '/sendFile',
method: 'POST'
};
http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
}).end();
In http request, how it's possible to send file uploaded in multipart form?
It depends. There are diverse strategies.
The simplest is to use the correct by using the .form() feature from request, sonmething like:
var form = req.form();
form.append('file', file_content, {
filename: 'myfile.ext',
contentType: 'corresponding content/type'
});
And then do the post Request
... or you can stream it and let request extract the data required
form.append('file', fs.createReadStream('path/to/file'));

How to export chunk in http.request in node.js

This http.request code is from http://nodejs.org/docs/v0.4.7/api/http.html#http.request.
How to export chunk in res.on ?
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
I'm not sure what you mean by "export" but perhaps you'd like to put the contents of the response into a local text file?
Here's how you might go about doing that:
var http = require('http');
var fs = require('fs');
var options = {
host: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
var response;
if(fs.existsSync('response.html'))
response = fs.readFileSync('response.html') + chunk;
else
response = chunk;
fs.writeFileSync('response.html', response);
});
});
// write data to request body
req.write('data\n');
req.write('data\n');
req.end();
Note that after each data event is fired, we're checking for an existing file with fs.existsSync, populating a response variable accordingly and then writing the response to a file again with fs.writeFileSync.
This wouldn't be much use on a server, as the synchronous nature of the file reads/writes would bottleneck your traffic, but it does highlight the general concept of responding to events and concatenating chunks.

Adding a new document in Couchdb ( iriscouch ) POST request fails with Status 500

A couple of months back,the code below worked perfectly and was used to add a new document in couchdb (iriscouch).
Now I'm getting a HTTP Status 500. Is there a workaround?
Code (in Node.js) :
var http=require('http');
var options = {
host: 'sbose78.iriscouch.com',
path: '/bosedb1',
method: 'POST',
headers:{
'Content-Type':'application/json',
'accept':'application/json'
}
};
var data={
'servings' : 4,
'subtitle' : "Delicious with fresh bread",
'title' : "Fish Stew------"
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
var body="";
res.on('data', function (chunk) {
body+=chunk;
console.log('BODY(inside listener):\n ' + body);
});
console.log('BODY (outside listener): ' + body);
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
//write data to request body
req.write(JSON.stringify(data));
req.end();
The response:
STATUS: 500
HEADERS: {"content-type":"text/plain","content-length":"239"}
BODY(inside listener):
Internal routing error
Sorry, we cannot connect to the intended server.
We have just been notified of this problem. We will correct it as soon as possible.
Feel free to contact us if you have any questions: support#iriscouch.com
Looks like http://www.iriscouch.com/ is down at the moment:
Host not found: www.iriscouch.com
Have you considered using an abstraction layer, at least to do http?
request
Your codebase is going to have a lot of http code if you don't :)
Personally I wrote and maintain the node.js CouchDB client which is based on request, if you are curious about it you can find out more at github

Categories

Resources