I am executing the following code to run HTTP POST request in Node.js application and it is working fine.
var http = require('http');
var request = require('request');
http.createServer(function handler(req, res) {
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end('Hello World\n');
var postData = {
'name': 'in2_instance',
'format': 'json',
'auto.offset.reset': 'earliest',
}
var options = {
url: 'http://localhost:8082/consumers/my_test_consumer',
method: 'POST',
body : JSON.stringify(postData),
headers: {
'Content-Type': 'application/vnd.kafka.v2+json'
},
}
request(options, function(error, response, body){
if(error) console.log(error);
else {
console.log(JSON.stringify(response));
// Upon Successful response, I need to execute another HTTP POST request here.
}
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
My question is, I need to execute 1 more HTTP POST request and 1 more HTTP GET request following with the each successful response. For example, from the above code, i need to execute another HTTP POST request upon successful response of the existing.
How can I call the other set of HTTP request one after another based on the successful response of the above?
Please advise or share me the reference.
You can do it in the same way as you are doing it for the first request.
var http = require('http');
var request = require('request');
http.createServer(function handler(req, res) {
//res.writeHead(200, {'Content-Type': 'text/plain'});
//res.end('Hello World\n');
var postData = {
'name': 'in2_instance',
'format': 'json',
'auto.offset.reset': 'earliest',
}
var options = {
url: 'http://localhost:8082/consumers/my_test_consumer',
method: 'POST',
body : JSON.stringify(postData),
headers: {
'Content-Type': 'application/vnd.kafka.v2+json'
},
}
request(options, function(error, response, body){
if(error) console.log(error);
else {
console.log(JSON.stringify(response));
var options1 = {
url: '<new URL>',
method: 'POST',
body : JSON.stringify(postData),
headers: {
'Content-Type': 'application/vnd.kafka.v2+json'
},
}
request(options1, function(error, response2, body) {
if(error) console.log(error);
else {
// Your GET request call
}
}
}
});
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Related
I'm just testing to see if my POST request to a website works, but it isn't outputting anything. When I use RunKit, it shows an output, but not in my powershell. Am I doing something wrong or is there no output? How can I make it show the output? Here is my code:
var request = require('request');
request.post(
'My_API_URL',
{ json: { "text":"this is my text" } },
function (error, response, body) {
console.log(body);
}
);
What i suggest you, is to update your code like this and try again:
var request = require('request');
var options = {
uri: 'My_API_URL',
method: 'POST',
json: {
"text":"this is my text"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
});
Let me know if the result is the same.
Check this link. You should do post requests like this:
var request = require('request');
var body = JSON.stringify({
client_id: '0123456789abcdef',
client_secret: 'secret',
code: 'abcdef'
});
request.post({
url: 'https://postman-echo.com/post',
body: body,
headers: {
'Content-Type': 'application/json'
}},
function (error, response, body) {
console.log(body);
}
);
Here I have a function hsResponse which is as below and in the console.log I am getting the proper body response when I run this standalone, but now I wanted call inside the app.get() method and I wanted to put the response of hsResponse to the app.get() API response.
After running the API I wanted to get the body (the value which is printed in the console.log) of hsResponse instead of Root API.
How can I achieve this?
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
console.log(body);
});
app.get('', (req, res) => {
res.send('Root API');
});
Why not use a function with a callback passed in parameter to handle the request result:
var hsResponse = function (done) {
// done is a function, it will be called when the request finished
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
if (error) return done(error);
done(null, body);
});
}
app.get('', (req, res) => {
hsResponse( function (err, body) {
if (err) throw err;
// get body here
res.send('Root API');
} );
});
Edit the code above buffers up the entire api response into memory (body) for every request before writing the result back to clients, and it could start eating a lot of memory if there were many requests at the same time. Streams, by using streams we could read one chunk at a time from the api response, store it into memory and send it back to the client:
app.get('', (req, res) => {
request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}).pipe(res);
});
Reference: stream handbook
You can just put the code inside:
app.get('', (req, res) => {
var hsResponse = request({
proxy: proxyUrl,
url: request_data.url,
headers: request_data.headers,
method: request_data.method,
form: oauth.authorize(request_data)
}, function (error, response, body) {
res.send(body); //<-- send hsResponse response body back to your API consumer
});
});
I have a need to send data from my NodeJS server to an outside server. I have tried many codes and searched for this alot, but not getting any proper working example or its not working in my case.
Here is my code:
app.get('/getFrom', function (req, res) {
var request = require('request');
// Try 1 - Fail
/*var options = {
url: 'http://example.com/synch.php',
'method': 'POST',
'body': {"nodeParam":"working"}
};
request(options, callback);
*/
// Try 2 - Fail
/* request({
// HTTP Archive Request Object
har: {
url: 'http://example.com/synch.php',
method: 'POST',
postData: {
params: [
{
nodeParam: 'working'
}
]
}
}
},callback)*/
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log("body " + body); // Show the HTML for the Google homepage.
res.send(body);
}
else{
console.log("Error " + error);
res.send(error);
}
}
/* ------ HTTP ------ */
var postData = querystring.stringify({
'nodeParam' : 'Hello World!'
});
// try 3 - Fail
/*var optionsHTTP = {
hostname: 'http://example.com',
port: 80,
path: '/synch.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req1 = http.request(optionsHTTP, function(res1){
console.log('STATUS: ' + res1.statusCode);
console.log('HEADERS: ' + JSON.stringify(res1.headers));
res1.setEncoding('utf8');
res1.on('data', function(chunk){
console.log('BODY: ' + chunk);
});
res1.on('end', function(){
console.log('No more data in response.')
})
});
req1.on('error',function(e){
console.log('problem with request:' + e.message);
});
// write data to request body
req1.write(postData);
req1.end();*/
/* ------ /HTTP ------ */
Please let me know where I am wrong
Not sure why exactly your request might be failing, but this is a simple and straightforward sample on using the request module in npm:
var request = require('request');
var postData = {
name: 'test123'
}
request({
url: 'http://jsonplaceholder.typicode.com/posts',
method: 'POST',
data: JSON.stringify(postData)
}, function(err, response) {
if (err) {
return console.error(err);
};
console.log(JSON.stringify(response));
})
This snippet makes a request to a rest API and display the result on the console. The response data is available in the response.body property.
I found a working and tested solution :
request({
url: 'http://example.com/synch.php', //URL to hit
qs: {nodeParam: 'blog example', xml: xmlData}, //Query string data
method: 'POST', //Specify the method
},callback);
I am trying to call API from the website and print out the JSON result.
but I cannot see the result.
Any thought to figure out this problem.
Thank you.
var http = require('http');
var data_info="";
http.createServer(function (req, res) {
sendJsontoAlchemy(outputMode());
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('end\n');
}).listen(1111)
console.log('Server is on');
function sendJsontoAlchemy()
{
requestNumber = JSONRequest.post(
"http://access.alchemyapi.com/calls/text/TextGetCategory",
{
apikey: "aaaaaa",
text : "Skateboard Mens Trousers t Shirt Wooden Fence",
outputMode : json,
jsonp:outputMode//call back function.
},
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
} else {
processError(exception);
}
});
}
function outputMode(response)
{
console.log("the result is =>");
console.log(JSON.stringify(response));
}
I'd suggest using the very useful module request for such things.
Example Code:
var request = require('request');
request({
method: 'POST',
uri: 'http://access.alchemyapi.com/calls/text/TextGetCategory',
body: 'apikey=1337abcd'+
'&text=Skateboard Mens Trousers t Shirt Wooden Fence' +
'&outputMode=json',
}, function(err, res, body){
result = JSON.parse(body);
console.log('Category: ', result.language);
console.log('Category: ', result.category);
});
If you need to output the thing from a server you can do a request({opts}).pipe(response) inside a server instead of specifying a callback.
var http = require('http');
var request = require('request');
http.createServer(function(req, res){
request({
method: 'POST',
uri: 'http://access.alchemyapi.com/calls/text/TextGetCategory',
body: 'apikey=1d416bcdde7cf8a360fad31701ac2c2ba57bc75f'+
'&text=Skateboard Mens Trousers t Shirt Wooden Fence' +
'&outputMode=json',
}).pipe(res);
}).listen(1111);
This module is 'request https://github.com/mikeal/request
I think i'm following every step but i'm missing an argument..
var request = require('request');
request.post({
url: 'http://localhost/test2.php',
body: "mes=heydude"
}, function(error, response, body){
console.log(body);
});
on the other end i have
echo $_POST['mes'];
And i know the php isn't wrong...
EDIT: You should check out Needle. It does this for you and supports multipart data, and a lot more.
I figured out I was missing a header
var request = require('request');
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost/test2.php',
body: "mes=heydude"
}, function(error, response, body){
console.log(body);
});
When using request for an http POST you can add parameters this way:
var request = require('request');
request.post({
url: 'http://localhost/test2.php',
form: { mes: "heydude" }
}, function(error, response, body){
console.log(body);
});
I had to post key value pairs without form and I could do it easily like below:
var request = require('request');
request({
url: 'http://localhost/test2.php',
method: 'POST',
json: {mes: 'heydude'}
}, function(error, response, body){
console.log(body);
});
If you're posting a json body, dont use the form parameter. Using form will make the arrays into field[0].attribute, field[1].attribute etc. Instead use body like so.
var jsonDataObj = {'mes': 'hey dude', 'yo': ['im here', 'and here']};
request.post({
url: 'https://api.site.com',
body: jsonDataObj,
json: true
}, function(error, response, body){
console.log(body);
});
var request = require('request');
request.post('http://localhost/test2.php',
{form:{ mes: "heydude" }},
function(error, response, body){
console.log(body);
});
Install request module, using npm install request
In code:
var request = require('request');
var data = '{ "request" : "msg", "data:" {"key1":' + Var1 + ', "key2":' + Var2 + '}}';
var json_obj = JSON.parse(data);
request.post({
headers: {'content-type': 'application/json'},
url: 'http://localhost/PhpPage.php',
form: json_obj
}, function(error, response, body){
console.log(body)
});
I have to get the data from a POST method of the PHP code. What worked for me was:
const querystring = require('querystring');
const request = require('request');
const link = 'http://your-website-link.com/sample.php';
let params = { 'A': 'a', 'B': 'b' };
params = querystring.stringify(params); // changing into querystring eg 'A=a&B=b'
request.post({
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, // important to interect with PHP
url: link,
body: params,
}, function(error, response, body){
console.log(body);
});
I highly recommend axios https://www.npmjs.com/package/axios install it with npm or yarn
const axios = require('axios');
axios.get('http://your_server/your_script.php')
.then( response => {
console.log('Respuesta', response.data);
})
.catch( response => {
console.log('Error', response);
})
.finally( () => {
console.log('Finalmente...');
});