How to make json-rpc request with Adonis - node.js

Am using Adonis to build a Bitcoin RPC system, so am making request with request.js Lib, so but the issue is with the callback when I make the request it works but I can't see send the response to the web endpoint, when I console the response from the RPC server it works fine but on postman it is blank.
getBlockCount({ response}){
const dataString = `{"jsonrpc":"1.0","id":"curltext","method":"getblockcount","params":[]}`;
const options = {
url: `http://${USER}:${PASS}#${HOST}:${PORT}/`,
method: "POST",
headers: headers,
body: dataString
};
const returnData;
const callback = (error, nextRes, body) => {
if (!error && nextRes.statusCode == 200) {
const data = JSON.parse(body);
console.log(data)
returnData = data;
response.status(200).send(returnData)
}
return response.send('data');
};
return request(options, callback);
// const options = requestOption(dataString);
// console.log(rpcRequest(options, callBack(response)));
}

I ended up using request-promise
And this is what it look like
async getBlockCount({req, response}){
return await rp(requestOption(`{"jsonrpc":"1.0","id":"curltext","method":"getblockcount","params":[]}`))
}
function requestOption(dataString) {
return {
url: `http://${USER}:${PASS}#${HOST}:${PORT}/`,
method: "POST",
headers: headers,
body: dataString
};
}

Related

I can't save the response of a request request in node.js

I created a login function that receives the mail and the pass, to receive the jwt. I have tried that the function returns the jwt but I have not succeeded.
This is the method that I have developed, it has a post request that sends the mail and pass parameters. in the resp variable I try to save the request response, but when invoking the function it prints :
undefined.
login(mail, pass) {
var options = {
'method': 'POST',
'url': 'https://inventario.demos.adlnetworks.com/api/login',
'headers': {
'Content-Type': 'application/json'
},
body: JSON.stringify({ "email": mail, "password": pass })
};
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
}
The problem is that "request" is an async function. You can't do this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
resp = response.body;
});
return resp;
Because "resp" always be undefined. You would need to do something like this
var resp;
var req = request(options, function(error, response) {
if (error) throw new Error(error);
return response.body;
});
But it wont work for you.
The short and easy solution is change the library to make http request, and use "async" and "await" to use easily async functions.
For example:
const fetch = require('node-fetch');
async function main(){
const data = await login();
console.log(data);
}
async function login(){
const url = "https://jsonplaceholder.typicode.com/posts";
const data = {
title: 'foo22222',
body: 'ba222r',
userId: 1
};
const response = await fetch(url, {
method: 'POST',
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
const json = await response.json()
return json;
}
main();
In this case i use "node-fetch" library and consume a backend (in login function) that create a post and return its response.

How to use Nodejs "request" work aysn in AWS Lambda?

When I'm trying to use "request" to access external API and get back the response in AWS Lambda, I don't know how to properly put my "return" code to return the response.
NodeJs 8.10
var request = require('request');
module.exports.sendcode = async (event) => {
let options = {
url: 'https://api.netease.im/sms/sendcode.action?' + content,
method: 'POST'
};
return await request(options, function (error, response, body) {
console.log(body);
return {
statusCode: 200,
body: JSON.stringify({
message: body,
input: event,
}),
};
});
};
When I run this code in serverless framework, I got a null response, there is nothing in the body, actually it should have at least the "input" attribute.
But console.log already logs the actual response from API.
It looks like my "return" code is not executed at all.
(If I remove async and await, then the program hangs until timeout)
Can anyone help how to modify this code to make it work?
Request does not use promises, so your await keyword is doing nothing. If you want to use promises with request, you need to find a library that supports promises, as noted here: https://www.npmjs.com/package/request#promises--asyncawait A popular option is https://github.com/request/request-promise-native
However, it is a simple matter to simply wrap a request in a promise, so that you don't need to use another dependency
var request = require('request');
const requestHandler = (options) => new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error) {
console.error(error);
reject(error);
} else {
console.log(response, body);
resolve({ response, body });
}
});
});
module.exports.sendcode = async (event) => {
let options = {
url: 'https://api.netease.im/sms/sendcode.action?' + content,
method: 'POST'
};
const { response, body } = await requestHandler(options);
return {
statusCode: 200,
body: JSON.stringify({
message: body,
input: event,
})
}
};
Instead of writing your own promise wrapper, maybe request-promise pacakge with promise wrapper on top of request by the same authors, would be of interest to you.
const rp = require('request-promise')
module.exports.sendcode = async (event) => {
let options = {
url: 'https://api.netease.im/sms/sendcode.action?' + content,
method: 'POST'
};
const body = await rp(options)
console.log(body);
return {
statusCode: 200,
body: JSON.stringify({
message: body,
input: event,
}),
};
};
If you want full response you've to simply set resolveWithFullResponse to true
let options = {
url: 'https://api.netease.im/sms/sendcode.action?' + content,
method: 'POST',
resolveWithFullResponse: true
};
// now response contains full respose
const response = await rp(options)
// response.body
// response.statusCode
Use Async/Await with promises. You cannot use Async-Await syntax with callback. Either you must write a promise wrapper for your 'request'callback or you can use request-promise module which is already available.
I have already provided answer for similar problem which you can refer here.
Undefined value after returning an array of values from a MySQL query in a different file

HTTP POST with node.js and request library isn't outputting anything

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);
}
);

Post request to external api

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);
}
};

How to download GitHub release asset from private repo using node

I would like to use node.js request module to download a release asset from a private repo. It works fine with the following cURL command:
curl -O -J -L \
-H "Accept: application/octet-stream" \
https://__TOKEN__:#api.github.com/repos/__USER__/__REPO__/releases/assets/__ASSET_ID__
but it fails when I try using the request module:
var request = require('request');
var headers = {
'Accept': 'application/octet-stream'
};
var API_URL = "https://__TOKEN__:#api.github.com/repos/__USER__/__REPO__"
var ASSET_ID = __ASSET_ID__
var options = {
url: `${API_URL}/releases/assets/${ASSET_ID}`,
headers: headers,
};
function callback(error, response, body) {
if (error) {
console.error(error);
}
console.log(response.statusCode)
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(options.url);
}
var req = request(options, callback);
console.log(req.headers)
I have double checked that the resulting URL when using node is the same as the one I use with cURL.
I receive a 403 statusCode in the response. I do not understand why.
UPDATE:
While looking at the headers that are actually sent, I have found that the it uses
{ Accept: 'application/octet-stream',
host: 'api.github.com',
authorization: 'Basic __DIFFERENT_TOKEN__' }
I do not understand why the token is changed.
some references: https://gist.github.com/maxim/6e15aa45ba010ab030c4
GitHub API requires a user agent (https://github.com/request/request#custom-http-headers)
It is also important to set the encoding to null in order to have a buffer and not a string in the body (Getting binary content in Node.js using request)
The working version of the code is thus:
var request = require('request');
var headers = {
'Accept': 'application/octet-stream',
'User-Agent': 'request module',
};
var API_URL = "https://__TOKEN__:#api.github.com/repos/__USER__/__REPO__"
var ASSET_ID = __ASSET_ID__
var options = {
url: `${API_URL}/releases/assets/${ASSET_ID}`,
headers: headers,
encoding: null // we want a buffer and not a string
};
function callback(error, response, body) {
if (error) {
console.error(error);
}
console.log(response.statusCode)
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(options.url);
}
var req = request(options, callback);
console.log(req.headers)
Thanks to Marko Grešak.

Resources