I have trying to send post call on https://api-mean.herokuapp.com/api/contacts with following data:
{
"name": "Test",
"email": "test#xxxx.in",
"phone": "989898xxxx"
}
But not get any response.
I have also tried it with postman it working fine. I have get response in postman.
I am using following nodejs code:
var postData = querystring.stringify({
"name": "Test",
"email": "test#xxxx.in",
"phone": "989898xxxx"
});
var options = {
hostname: 'https://api-mean.herokuapp.com',
path: '/api/contacts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
};
var req = http.request(options, function (res) {
var output = '';
res.on('data', function (chunk) {
output += chunk;
});
res.on('end', function () {
var obj = JSON.parse(output.trim());
console.log('working = ', obj);
resolve(obj);
});
});
req.on('error', function (e) {
console.error(e);
});
req.write(postData);
req.end();
Am I something missing?
How to send http post call from node server?
I recommend you to use the request module to make things easier.
var request=require('request');
var json = {
"name": "Test",
"email": "test#xxxx.in",
"phone": "989898xxxx"
};
var options = {
url: 'https://api-mean.herokuapp.com/api/contacts',
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
json: json
};
request(options, function(err, res, body) {
if (res && (res.statusCode === 200 || res.statusCode === 201)) {
console.log(body);
}
});
For sending HTTP-POST call from nodejs, you might need to use the request module
Sample:
var request = require('request');
request({
url: "some site",
method: "POST",
headers: {
// header info - in case of authentication enabled
},
json:{
// body goes here
}, function(err, res, body){
if(!err){
// do your thing
}else{
// handle error
}
});
Related
I want to send a POST Request to Twilio when an Intent is called from my Alexa Skill. When testing the Code, there are no errors, but the Request doesn't seem to go through. Testing the POST Request in Postman works.
function postToTwilio() {
var http = require("https");
var postData = JSON.stringify({
'To' : '1234567',
'From': '1234546',
'Url': 'https://handler.twilio.com/twiml/blablabla',
});
var options = {
"method": "POST",
"hostname": "https://api.twilio.com",
"path": "/12344/Accounts/blablablablba/Calls.json",
"headers": {
"Authorization": "Basic blblablablablabla",
"Content-Type": "application/x-www-form-urlencoded",
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.write(postData);
req.end();
}
First of all, a request is a async call so you need to make alexa wait for the response.
To do that, you need to use async await process and using promises.
var postData = JSON.stringify({
'To' : '1234567',
'From': '1234546',
'Url': 'https://handler.twilio.com/twiml/blablabla',
});
var options = {
"method": "POST",
"hostname": "https://api.twilio.com",
"path": "/12344/Accounts/blablablablba/Calls.json",
"headers": {
"Authorization": "Basic blblablablablabla",
"Content-Type": "application/x-www-form-urlencoded",
}
};
function get(options) {
return new Promise(((resolve, reject) => {
const request = https.request(options, (response) => {
response.setEncoding('utf8');
let returnData = '';
if (response.statusCode < 200 || response.statusCode >= 300) {
return reject(new Error(`${response.statusCode}: ${response.req.getHeader('host')} ${response.req.path}`));
}
response.on('data', (chunk) => {
returnData += chunk;
});
response.on('end', () => {
resolve(JSON.parse(returnData));
});
response.on('error', (error) => {
reject(error);
});
});
request.write(postData)
request.end();
}));
}
Then, when you call this get function:
let response = await get(options)
I haven't tested as a whole but that is the base skeleton.
Let me know if that works.
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);
}
};
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
[EDIT]
I figured it out. The code ends up like this:
//getTrelloJSON.js
var request = require('request');
'use strict';
function getProjJSON(requestURL, callback){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
callback(data);
}
});
}
module.exports.getProjJSON = getProjJSON;
And
//showData.js
var getJSON = require('./getTrelloJSON');
getJSON.getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json', (result) => {
var lists = result.lists;
console.log(lists);
});
I run node showData.js and it gets the json and then I can manipulate it as needed. I printed just to show it works.
[EDIT END]
I'm new to node.js and I am facing a noob problem.
This code is supposed to request a JSON from a public trello board and return an object with a section of trello's json (lists section).
The first console.log() does not work but the second does.
How do I make it wait for the completion of getProjJSON() before printing it?
var request = require('request');
'use strict';
//it fails
console.log(getProjJSON('https://trello.com/b/saDpzgbw/ld40-gem-sorceress.json'));
function getProjJSON(requestURL){
request.get({
url: requestURL,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error:', err);
} else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
//it works
console.log(data.lists);
return data.lists;
}
});
}
Node.js is all about callbacks.
And here you just not register the callbacks for data.
var client = require('http');
var options = {
hostname: 'host.tld',
path: '/{uri}',
method: 'GET', //POST,PUT,DELETE etc
port: 80,
headers: {} //
};
//handle request;
pRequest = client.request(options, function(response){
console.log("Code: "+response.statusCode+ "\n Headers: "+response.headers);
response.on('data', function (chunk) {
console.log(chunk);
});
response.on('end',function(){
console.log("\nResponse ended\n");
});
response.on('error', function(err){
console.log("Error Occurred: "+err.message);
});
});
or here is a full example, hope this solve your problem
const postData = querystring.stringify({
'msg' : 'Hello World!'
});
const options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
const req = http.request(options, (res) => {
console.log(`res_code: ${res.statusCode}`);
console.log(`res_header: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`res_data: ${chunk}`);
});
res.on('end', () => {
console.log('end of response');
});
});
req.on('error', (e) => {
console.error(`response error ${e.message}`);
});
//write back
req.write(postData);
req.end();
I'm trying to generate a notification from my REST service. The drawback is that not send, although fcm.googleapis.com/fcm/send responds that was successful.
This I do in two ways, first by the module http:
var http = require('http');
var options = {
'hostname': 'fcm.googleapis.com',
'path': '/fcm/send',
'method': 'POST',
'headers': {
'Authorization': 'key=<Key Server>',
'Content-Type': "application/json"
}
};
var data = {
'to':tokenPush,
'notification':notification
};
var requestHttp = http.request(options, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
});
});
requestHttp.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
requestHttp.end(JSON.stringify(data));
The other way is through a command from the shell:
var exec = require('child_process').exec;
var cmd = 'curl -X POST --header "Authorization: key=<Key Server>" ';
cmd += '--Header "Content-Type: application/json" https://fcm.googleapis.com/fcm/send ';
cmd +='-d \'{"to":"<Token Client>","notification":{"title":"Validación","body":"'+(new Date()).getTime()+'","sound":"default"}}\'';
console.log("=====================================");
console.log(cmd);
console.log("=====================================");
exec(cmd, function(error, stdout, stderr) {
if (error) {
console.log("=====================================");
console.error('exec error:'+error);
}
console.log("=====================================");
console.log('stdout: '+stdout);
console.log('stderr: '+stderr);
});
In both cases the answer is:
{ "Multicast_id": "success": 1, "failure": 0, "canonical_ids": 0, "results": [{ "message_ID": ""}]}.
The code for the shell works correctly when I run it from a separate file with the "node" command.
What I can be wrong?
Use an fcm wrapper. I've used 'fcm-node' link: https://www.npmjs.com/package/fcm-node
Just install it with npm install fcm-node --save
Usage
var FCM = require('fcm-node');
var serverKey = '';
var fcm = new FCM(serverKey);
var message = { //this may vary according to the message type (single recipient, multicast, topic, et cetera)
to: 'registration_token',
collapse_key: 'your_collapse_key',
notification: {
title: 'Title of your push notification',
body: 'Body of your push notification'
},
data: { //you can send only notification or only data(or include both)
my_key: 'my value',
my_another_key: 'my another value'
}
};
fcm.send(message, function(err, response){
if (err) {
console.log("Something has gone wrong!");
} else {
console.log("Successfully sent with response: ", response);
}
});
Your code is not clean.
This should work. Replace CLIENT_PUSH_ID and YOUR_AUTH_KEY to real
var http = require('http');
var message = {
"to": "CLIENT_PUSH_ID",
"notification": {
"title": "Validación",
"body": (new Date()).getTime(),
"sound": "default"
}
};
var postData = JSON.stringify(message);
var options = {
hostname: 'fcm.googleapis.com',
path: '/fcm/send',
method: 'POST',
headers: {
'Content-Length': postData.length,
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'key=YOU_AUTH_KEY'
}
};
var requestHttp = http.request(options, function (res) {
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log(chunk);
});
res.on('error', function (e) {
console.log('error:' + e.message);
});
});
requestHttp.write(postData);
requestHttp.end();
requestHttp.on('error', function (e) {
console.log(e);
});
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);