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.
Related
I am calling below url with get https request using Node.js, here i need to send the session with cookie, since i know the vallue of cookie.
var URL = require('url-parse');
var appurl = "https://test.somedomain.com"
var https = require('https');
var url = new URL(appurl);
var options = {
host: url.host,
url: appurl,
path: url.pathname + url.query,
method: 'GET',
headers: {
"Set-Cookie": "cookiValue1=abcdesg"
}
};
var req = https.request(options, function (res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
// console.log(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);
});
req.write('data\n');
req.write('data\n');
req.end();
The header should be Cookie instead of Set-Cookie
Set-Cookie is used by the server to set a cookie on clients. Header Cookie is used to send a cookie to server by client.
So nodejs server it's not a browser which have window and document
try to send the same request in js client side not nodejs
You can set cookie only here
see POINTERs in the bottom
var URL = require('url-parse');
var https = require('https');
var appurl = "https://stackoverflow.com/"
var url = new URL(appurl);
var options = {
host: url.host,
url: appurl,
path: url.pathname + url.query,
method: 'GET',
headers: {
"Cookie": "1111111111=abcdesg", // POINTER its unfortunately useless
"Set-Cookie": "11111111=abcdesg" // POINTER its unfortunately useless
}
};
var req = https.request(options, function (res) {
console.log('before HEADERS: ' + JSON.stringify(res.headers));
res.headers.cookiValue1 = 'abcdesg'; // POINTER
console.log('after HEADERS: ' + JSON.stringify(res.headers));
});
req.on('error', function (e) {
console.log('problem with request: ' + e.message);
});
req.write('data\n');
req.write('data\n');
req.end();
im trying to send multiple http put request to my server, but i only manage to send one JSON to the database, what i am missing here
var data1 = JSON.stringify(require('./abc.json')),
data2 = JSON.stringify(require('./abe.json')),
data3 = JSON.stringify(require('./abd.json'));
var put_data = [data1,data2,data3];
async.each(put_data, function(data, callback){
var post_options = {
hostname: config.serviceHost,
port : '80',
path : '/API/Nag',
method : 'PUT',
headers : {
'Content-Type': 'application/json',
'Authorization': config.secret
}
};
post_req = http.request(post_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('Response: ', chunk);
});
res.on('end', function () {
callback();
});
});
post_req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
post_req.write(data); //posting data
post_req.end();
}, function(err){
console.log('All requests done!')
});
even tho it send 3 http request, all three request contains same data
The variable post_req has global scope. Meaning the value of post_req can be accessed and modified outside async.each function.
The solution is to add one var before post_req that would restrict the variable scope to async and also spawns a new variable for each iteration.
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'));
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.
Inside the code, I want to download "http://www.google.com" and store it in a string.
I know how to do that in urllib in python. But how do you do it in Node.JS + Express?
var util = require("util"),
http = require("http");
var options = {
host: "www.google.com",
port: 80,
path: "/"
};
var content = "";
var req = http.request(options, function(res) {
res.setEncoding("utf8");
res.on("data", function (chunk) {
content += chunk;
});
res.on("end", function () {
util.log(content);
});
});
req.end();
Using node.js you can just use the http.request method
http://nodejs.org/docs/v0.4.7/api/all.html#http.request
This method is built into node you just need to require http.
If you just want to do a GET, then you can use http.get
http://nodejs.org/docs/v0.4.7/api/all.html#http.get
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
(Example from node.js docs)
You could also use mikeal's request module
https://github.com/mikeal/request
Simple short and efficient code :)
var request = require("request");
request(
{ uri: "http://www.sitepoint.com" },
function(error, response, body) {
console.log(body);
}
);
doc link : https://github.com/request/request
Yo can try with axios
var axios = require('axios');
axios.get("http://www.sitepoint.com", {
headers: {
Referer: 'http://www.sitepoint.com',
'X-Requested-With': 'XMLHttpRequest'
}
}).then(function (response) {
console.log(response.data);
});