Trying to post api request - node.js

I having problem with making a API call to an external site.
I need to send a POST request to http://api.turfgame.com/v4/users with headers Content-type: application/js. But when I run this code it only loads and nothing more.
var request = require('request');
var options = {
uri: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {
"name": "username"
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
res.send(response.body);
}
});
The body need to be posted in json formate [{'name': 'username'}].
Can someone tell me what I have done wrong?

There are a few things wrong:
the address property in the "options" object should be "url" not
"uri"
you can use the "json" property instead of body
"res" is undefined in your response handler function
if you want the body to be an array, it needs to be surrounded in square brackets
here's a working sample that just logs the response:
var request = require('request');
var options = {
url: 'http://api.turfgame.com/v4/users',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: [{
"name": "username"
}]
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(response.body);
}
});

Related

node.js + request => response showing junk response

I am using the node.js + request for send HTTP request to URL. I required the JSON response, but I get junk character.
Here is my node.js code
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
But I received response in junk characters.
I need result in jSON format, What is wrong in this request?
I found the issue, reason is that API response send in gZip format. Here is the change we have to made here. Just enable gzip: true that resolve the things.
var request = require('request');
var post_data = { UserName: "xxxxx", Password: "xxxxx" };
var post_options = {
url: 'http://xxxxxxx.info/api/CoreUser/cognitoLogin',
method: 'POST',
gzip: true,
form: post_data,
headers: {
'AppID': 'zNiphaJww8e4qYEwJ96g555HTAAbAXdj',
'OAuth': 'xxxxxxxxxxxxxxxxxx',
//'User-Agent': 'Super Agent/0.0.1',
'Content-Type': 'application/json;charset=UTF-8',
}
};
// Set up the request
request(post_options, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});
You are missing { json: true } in request call
request(post_options, { json: true }, function (error, response, body) {
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
console.log("200");
console.log(response);
}
});

How to make a get request in nodejs

I'm trying make a get request to get user online in a channel on my server, but i always reveive all user of my server.
I have used request module, but it not working, seem it not pass parameter "_id" on request
in curl
curl -s -G \
-H "X-Auth-Token: Qv5vMPB_6aMCSv5ayQAbQCXkSsBzra_K6BbAqc7S0Fr" \
-H "X-User-Id: 34YYb2cqqDaFz53ib" \
-H "Accepts: application/json" \
--data-urlencode 'query={"_id": "FC77kqfNrH39wEaKG"}' \
http://localhost:3001/api/v1/channels.online
result as I expert
{
"online": [
{
"_id": "D539dgygpWrYrNyFz",
"username": "tranhoang"
},
{
"_id": "34YYb2cqqDaFz53ib",
"username": "mybot"
}
],
"success": true
}
code use request module
var request = require('request');
var headers = {
'X-Auth-Token': 'Qv5vMPB_6aMCSv5ayQAbQCXkSsBzra_K6BbAqc7S0Fr',
'X-User-Id': '34YYb2cqqDaFz53ib',
'Accepts': 'application/json'
};
var options = {
url: 'http://localhost:3001/api/v1/channels.online',
headers: headers,
form: {
query: '{"_id": "FC77kqfNrH39wEaKG"}'
}
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
console.log(response);
}
}
request(options, callback);
and result
{
"online": [
{
"_id": "D539dgygpWrYrNyFz",
"username": "tranhoang"
},
{
"_id": "34YYb2cqqDaFz53ib",
"username": "mybot"
},
{
"_id": "DkiEXfaXRA5EffnHb",
"username": "sp2"
}
],
"success": true
}
sp2 is not join in channel that have "_id" in form, what can i do, please help me!!
To make HTTP GET request in Node.js using request module, you don't need form in options object. Instead, qs in options is the right choice.
The code would look like:
var request = require('request');
var headers = {
'X-Auth-Token': 'Qv5v...S0Fr',
'X-User-Id': '34YY...53ib',
'Accepts': 'application/json'
};
var options = {
uri: 'http://localhost:3001/api/v1/channels.online',
headers: headers,
qs: {
query: {"_id": "FC77kqfNrH39wEaKG"}
},
method: 'GET'
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
console.log(response);
}
}
request(options, callback);

Facebook Messenger: How to send multiple messages with nodejs

I just want to send a messages to all the subscribers with nodejs.
This is my code ( I have hidden the PSID below ):
app.get('/helloguys', function (req, res) {
var messageData = {
batch: [
{recipient: {id: "..."}},{recipient: {id: "..."}}
],
message: {
text: "Hi guys :)",
metadata: "DEVELOPER_DEFINED_METADATA"
}
};
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: token },
method: 'POST',
json: messageData
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Ok", response.statusCode);
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
res.send('Hi :)')
})
I get this in the nodejs console:
Ok 200
but users don't receive the message.
Why ?
EDIT for Lix:
body:
2017-10-18T13:38:43.538998+00:00 app[web.1]: [ { code: 400,
2017-10-18T13:38:43.538999+00:00 app[web.1]: headers: [Object],
2017-10-18T13:38:43.538999+00:00 app[web.1]: body: '{"error":{"message":"Unsupported get request. Please read the Graph API documentation at https:\\/\\/developers.facebook.com\\/docs\\/graph-api","type":"GraphMethodException","code":100,"error_subcode":33,"fbtrace_id":"Dd6+kHN7Tl+"}}' },
EDIT for CBroe:
var messageData = {
batch: [
{method:"POST", message: "Hello", recipient: {id: "1552389158161227"}},{method:"POST", message: "Hello", recipient: {id: "1419003191530571"}}
]
};
It doesn't work
EDIT for CBroe 2:
app.get('/helloguys', function (req, res) {
var batch = [
{method:"POST", body: "message=Test status update&recipient=..."},
{method:"POST", body: "message=Test status update&recipient=..."}
];
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: { access_token: token },
method: 'POST',
json: batch
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("ok", response.statusCode, response.statusMessage, response);
res.send('hi')
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});
})
And now I get:
2017-10-18T15:36:05.981999+00:00 app[web.1]: Failed calling Send API 400 Bad Request { message: '(#100) The parameter recipient is required',
2017-10-18T15:36:05.982009+00:00 app[web.1]: type: 'OAuthException',
2017-10-18T15:36:05.982010+00:00 app[web.1]: code: 100,
2017-10-18T15:36:05.982011+00:00 app[web.1]: fbtrace_id: 'EJLQgP9UoMT' }
As per FB dev docs (they stated somewhere within the docs, and not very obvious)
Note the URLEncoding for the body param
Also, multiple POST requests (batched requests):
While GET and DELETE operations must only have a relative_url and a method field, POST and PUT operations may contain an optional body field.
And >>
This should be formatted as a raw HTTP POST body string, similar to a URL query string.
Also, this type of request should be made as multipart/form-data.
Then, batch request requirements are:
(1) to be multipart/form-data;
(2) consist of URLEncoding strings in 'body' parameter;
(3) batch request should be raw HTTP POST body string.
Node.js request module could send form-data (through form-data module). See docs
So, your code should be like this >>
app.get('/helloguys', function (req, res) {
var batchUrl = 'https://graph.facebook.com';
var r = request.post(batchUrl, function(error, response, body) {
if (error) {return console.log("error\n", error)};
console.log("successfull\n", body) //but fb sends error in body message, so check body.error for any errors
});
var form = r.form();
var multipleMessages = [];
var message = "message=" + encodeURIComponent(JSON.stringify(
{
"text": "​Hi guys :)"
}
));
//loop throught user IDs (PSIDs)
for (var i=0; i<users; i++) {
var recipient = "recipient=" + encodeURIComponent(JSON.stringify({"id": users[i].id}));
var batchMessage = {
"method": "POST",
"relative_url":"v2.6/me/messages",
"body": recipient + "&" + message
};
multipleMessages.push(batchMessage);
}
form.append("access_token", token)
form.append("batch", JSON.stringify(multipleMessages));
res.send('Hi :)')
})
Try to move res.send('Hi') inside your request callback:
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log("Ok", response.statusCode);
res.send('Hi');
} else {
console.error("Failed calling Send API", response.statusCode, response.statusMessage, body.error);
}
});

Async request module in Node.js

I am creating a project using Node.js. I want to call my requests in parallel. For achieving this, I have installed the async module. Here is my code:
var requests = [{
url:url,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer ' + req.cookies.apitoken
},
json: finalArr,
}];
async.map(requests, function(obj, callback) {
// Iterator function
request(obj, function(error, response, body) {
if (!error && response.statusCode == 200) {
// Transform data here or pass it on
var body = JSON.parse(body);
callback(null, body);
}
else {
var body = JSON.stringify(body);
console.log(body)
callback(error || response.statusCode);
}
});
})
I got undefined every time in console.log(body). When I am using GET requests using this module for other requests then everything works fine.
It looks like you're using the request module, but didn't tag it as such.
If I'm right, then your options object is incorrect, from the documentation there's not a data key that's respected. Instead, you should use body or formData or json depending on what kind of data you're pushing up. From your headers, I'd go with json.
var requests = [{
url:url,
method: 'POST',
headers: { // Content-Type header automatically set if json is true
'Authorization': 'Bearer ' + req.cookies.apitoken
},
json: finalArr,
}];

node js send post request with raw request body

var req ={
"request": {
"header": {
"username": "name",
"password": "password"
},
"body": {
"shape":"round"
}
}
};
request.post(
{url:'posturl',
body: JSON.stringify(req),
headers: { "content-type": "application/x-www-form-urlencoded"}
},
function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
}
);
I want to send raw request body in req variable . It is working on postman but in node js i am not able to send the raw json as request body for post request .
You are trying to send JSON (your req variable) but you are parsing it as a String (JSON.stringify(req)). Since your route is expecting JSON, it will probably fail and return an error. Try the request below:
request.post({
url: 'posturl',
body: req,
json: true
}, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body)
}
});
Instead of setting your headers, you can just add the option json: true if you are sending JSON.
Change the Content-Type to application/json, since your body is in JSON format.
Adding the 'Content-Length' in the header for the string that is added in the body , will resolve this issue.
It worked for me.
headers:{"Cache-Control": "no-cache", "Content-Type":"application/json;charset=UTF-8",'Content-Length': req.length}

Resources