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);
Related
after a post request from an ajax call in angularjs, i want to send the request params from angularjs to an external api. I get all params i want. But I don't know, how i can make a new post request to the api, inside my nodejs url. I need this step to nodejs.
This is my Code
router.post({
url: '/user/:id/sw'
}, (req, res, next) => {
var userId = req.pramas.id;
var firstName = req.pramas.firstName;
var lastName = req.pramas.lastName;
var data = 'test';
res.send(200, data);
});
I found some solutions like this on: (just example code)
request({
uri: 'http://www.giantbomb.com/api/search',
qs: {
api_key: '123456',
query: 'World of Warcraft: Legion'
},
function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
res.json(body);
} else {
res.json(error);
}
}
});
but this doesn't work. How I can make a new Post Request with the req.params to an external api? Also i need a Response from the api..
Thanks for help and Ideas :)
Its req.params not req.pramas
Try this
var request = require('request');
router.post({
url: '/user/:userId/shopware'
}, (req, res, next) => {
var params = req.params;
request.get({
uri: 'http://www.giantbomb.com/api/search',
qs: params // Send data which is require
}, function (error, response, body) {
console.log(body);
});
});
Try this,
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'http://localhost.com/test-url',
body: {
foo: 'bar'
},
json: true
// JSON stringifies the body automatically
};
request(options)
.then(function (response) {
// Handle the response
})
.catch(function (err) {
// Deal with the error
})
var request = require("request");
exports.checkstatus = async (req, res) => { //this is function line you can remove it
try {
var options = {
method: 'POST',
url: 'https://mydoamin/api/order/status',
headers:
{
signature: '3WHwQeBHlzOZiEpK4yN8CD',
'Content-Type': 'application/json'
},
body:
{
NAME: 'Vedant',
ORDERID: 'ORDER_ID1596134490073',
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body); //get your response here
});
} catch (error) {
return fail(res, error.message);
}
};
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/');
Using the Instagram API i am calling the endpoint.
https://api.instagram.com/v1/tags/MYTAG/media/recent?access_token=MYACCESSTOKEN
I am getting different results returned when calling from my app vs calling from apigee.com. The difference being the access_token.
When i use https://apigee.com/console/instagram and make the instagram api call i get back 8 images. (after logging in with my instagram creditials), which is what i would expect.
if i log in with the same creditials using my nodejs app , i get a different auth token(which you would assume), but i get an empty data set back.
{ pagination: { next_min_id: 'STUFF', min_tag_id: 'STUFF' },
meta: { code: 200 },
data: []
}
I must be missing something simple.
Can anyone see what i may be doing wrong in my nodejs code
Thanks for any help
This is the nodejs code:::
var https = require('https');
var http = require('http');
var express = require('express');
var app = express();
var fs = require("fs");
var client_id = "CLIENT_ID";
var client_secret = "CLIENT_SECRET";
var redirect_uri = 'https://MYDOMAIN/handleauth';
var authorize_link = 'https://api.instagram.com/oauth/authorize/?client_id=' + client_id + '&redirect_uri=' + redirect_uri + '&response_type=code';
app.get('/authorize_user', function (req, res) {
res.redirect(authorize_link);
});
app.get('/handleauth', function (req, res) {
res.send("ok");
if (req.query['code']) {
var request = require('request');
var post_data = {
'client_id': client_id,
'client_secret': client_secret,
'grant_type': 'authorization_code',
'redirect_uri': redirect_uri,
'code': req.query['code']
};
var headers = {
'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/x-www-form-urlencoded'
}
var post_options = {
url: 'https://api.instagram.com/oauth/access_token',
method: 'POST',
headers: headers,
form: post_data
};
request(post_options, function (error, response, body) {
if (error || response.statusCode != 200) {
console.error(error);
} else {
var pbody = JSON.parse(body);
console.log('Response: ' + pbody);
console.log('pbody.access_token: ' + pbody.access_token);
var options = {
url: 'https://api.instagram.com/v1/tags/MYTAG/media/recent?access_token='+pbody.access_token,
method: 'GET'
};
request(options, function (error, response, body) {
if (error && response.statusCode != 200) {
console.error(error);
}else{
var jsonobjArr = JSON.parse(body);
console.log(jsonobjArr);
}
});
}
});
}
});
var options = {
key: fs.readFileSync("/ssl_certs/me.key"),
cert: fs.readFileSync("/ssl_certs/me_bundle.crt")
};
https.createServer(options, app).listen(4000, function () {
console.log("HTTPS Express Instagram server listening on port " + 4000);
});
You're in Sandbox Mode.
Data is restricted to the 10 users and the 20 most recent media from each of those users.
I realized this because I could only receive data from the tags I've posted.
Your question helped me figure out how to generate the access token. I couldn't get node-rest-client to work. Thanks!
My suggestion is to build the best application you can to mitigate the approval process.
Here's my code in nodeJS.. When I deployed it to my local it is always run ok, but when i deployed it on the production I always got an error "ArrayBuffer not defined". Can someone tell me what it caused? I'll tried to add ArrayBuffer but I got the same error. Thanks
var svr = http.createServer(function(req, resp) {
var response = [];
var calls = [];
var windowLiveId;
var huaweiReturnCode;
var serviceId = apigeeAccess.getVariable(req,'subscription.serviceid');
var ericssonRequestBody = {"offerId":serviceId,"generateBillingRecord":true };
calls.push(function(callback) {
http.get('http://butcha-test.apigee.net/v1/accounts/', function (resource) {
resource.setEncoding('binary');
resource.on('data', function (data) {
windowLiveId = JSON.parse(data).AccountId;
request.post({
url:'http://butcha-test.apigee.net/v1/erickson/'+windowLiveId,
method: 'POST',
headers:{
'Content-Type': 'application/json'
},
body: JSON.stringify(ericssonRequestBody)
}, function(error,res,body){
apigeeAccess.setVariable(req,"ericsonStatus",(/2[0-9][0-9]/.test(res.statusCode)) ? "success":"fail");
apigeeAccess.setVariable(req,"ericsonStatusCode",res.statusCode);
callback();
});
});
});
});
calls.push(function(callback){
request.post({
url:'http://morning-sea-3467.getsandbox.com/mockOverseaBossServiceSoapBinding',
method: 'POST',
headers: {'content-type' : 'application/xml'},
body: huaweiSoapRequest
}, function(error,res,body){
response.push(body);
var tag = "<bean:returnCode>";
var x = body.indexOf(tag) + tag.length;
huaweiReturnCode = body.substring(x, (x+1));
apigeeAccess.setVariable(req,"huaweiReturnCode",huaweiReturnCode);
apigeeAccess.setVariable(req,"huaweiStatusResult",(huaweiReturnCode =="0")? "success":"fail");
callback();
});
});
async.parallel(calls, function(){
resp.end(str2ab(response.toString));
});
});
Maybe because of the version of your Apigee? Because older version of Apigee is not supported nodeJs
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...');
});