Iam using request() in node js to call external apis.
if (req.method == 'GET')
options.qs = req.query;
else
options.form = req.body;
request(options, function(error, response, body) {
if (error || [constants.response_codes.success, constants.response_codes.internal_server_error, constants.response_codes.error, constants.response_codes.unauthorized].indexOf(response.statusCode) < 0) return next(true);
return next(null, { statuscode: response.statusCode, data: response.body });
});
It is working with req.method GET,POST,PUT and DELETE.But I need to send multipart/form-data for sending files from the client side to laravel project via node js.Iam using body-parser in node js for parsing the request.How can it be achieved by using request() in node js to send file.
You can try this
const options = {
method: "POST",
url: "Your URL",
port: 443,
headers: {
"Authorization": "Basic " + auth,
"Content-Type": "multipart/form-data"
},
formData : {
"image" : fs.createReadStream("./images/src.png")
}
};
request(options, function (err, res, body) {
if(err) console.log(err);
console.log(body);
});
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);
}
);
I am using node js and making a call to spotify API and receive the response in body object, as shown in below code:
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
console.log(body)
});
This gives me output:
But now when I try to access the body object outside the function I get undefined. I think the problem is that I am making an asynchronous call and so before the response is received the statements where I make use of body variable outside function are executed. But I am a bit confused about how to get to the solution.
Any help is appreciated
Edit:
request.get(options, function(error, res, body) {
console.log(body)
response.render('user_account.html', {
data: body
})
});
And it gives the output:
Use promise.
You can try following:
const apiCall = () => {
return new Promise((resolve, reject) => {
var options = {
url: 'https://api.spotify.com/v1/me',
headers: { 'Authorization': 'Bearer ' + access_token },
json: true
};
request.get(options, function(error, res, body) {
if(error) reject(error);
console.log(body);
resolve(body);
});
});
}
apiCall().then((body) => {
// do your things here
})
.catch((err) => console.log(err));
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 have a node instance using express. It makes call to a JAVA backend. When I receive the response I check if there is a content-disposition header and react accordingly with the type of file.
The content of the response.body is the pdf in binary content. With content-type header "application/pdf;charset=UTF-8". I also receive a Content-Transfer-Encoding header set to binary.
If I call my JAVA backend directly from a REST client, everything is fine and I can view the raw body or download the file.
If I go with node, the PDF is blank. But has the correct number of pages.
Here's how I forward the respond to the frontend.
res.status(response.statusCode).set('content-disposition', response.contentDisposition).set('Content-Type', response.contentType).send(response.body);
Is it possible Express is converting it to some default encoding before I can even have access to the response ?
All I want to do is take the body response from my java backend ajust the headers and send it back to the frontend.
Thank you
EDIT
This is the options I pass to my request function
method=GET, user=username, pass=password, uri=http://appsjava-veo01.hostname:8081/VEO/r/pap/pap5001/produire/311, Content-Type=*/*, Accept=*/*
Calling my http handler, and in the callback sending back the response
httpRequest(options, req, res, function(err, response){
if (err){
return next(err);
}else{
if (response.jsonResponse){
res.status(response.statusCode).set('Content-Type', 'application/json').send(response.jsonResponse);
}else{
if (response.contentDisposition){
res.status(response.statusCode).set('Content-Disposition', response.contentDisposition).set('Content-Type', response.contentType).send(response.messageHtml);
}else {
res.status(response.statusCode).set('Content-Type', 'application/json').send(JSON.stringify({
success: response.success,
message: response.message,
messageHtml: response.messageHtml,
dateJour: response.dateJour,
usager: response.usager
}));
}
}
}
});
var httpRequest = function(options, req, res, callback) {
var errorMsg, dateJour;
ASQ(function (done) {
request(options, function (error, response) {
if (!response) {
done.fail(error);
} else {
done(response);
}
});
})
.then(function (done, response) {
var bodyResponse,
httpResponse,
jsonResponse,
contentDisposition = response.headers['content-disposition'],
usager = (req.session.cas) ? req.session.cas.user : 'nocas';
dateJour = new Date().toJSON();
//Validation et aiguillage selon les status code http
if (response.statusCode === 401) {
req.session.pt = '';
httpResponse = {
'statusCode': 401,
'success': false,
'message': '401 - Authorization requise',
'messageHtml': response.body,
'dateJour': dateJour,
'jsonResponse': null,
'usager': usager
};
return callback(null, httpResponse);
} else if (response.statusCode.toString().charAt(0) === '2' || response.statusCode === 406 || response.statusCode === 428) {
if (contentDisposition) {
var contentType = utils.extractContentType(contentDisposition);
httpResponse = {
'statusCode': response.statusCode,
'success': true,
'message': 'Téléchargement du fichier',
'messageHtml': response.body,
'dateJour': dateJour,
'jsonResponse': null,
'contentDisposition': contentDisposition,
'contentType': contentType,
'usager': usager
};
return callback(null, httpResponse);
...................
I have to write some code with Node.JS for an API documentation, but I tried the last few days all the solutions I could found on the web (including Stack of course) without succes...
My API use HTTP Digest Auth and that's the problem, I was able to connect, that's was not a big deal but everytime I got the same return :
Got response : 401
HTTP Digest Authentication required for "api.example.com"
You can show my base code below without auth! Because I don't know what I can do after all the try I did :
var http = require('http')
var options = {
host: 'api.example.com',
path: '/example/1.xml',
};
var request = http.get(options, function(res){
var body = "";
res.on('data', function(data){
body += data;
})
res.on('end', function(){
console.log('Got response : ' + res.statusCode);
console.log(body);
})
res.on('error', function(e){
console.log('Got error : ' +e.message);
});
});
One of my last try was to use this module https://npmjs.org/package/request but he doesn't work too as everytime I got 401 !
For more information I was able to connect and GET the information I needed from my API with Ruby, Python, php, and Java so I'm sure my API is working well and the information I pass are correct.
I use the last stable of Node v0.10.11 !
If someone can help me or have a solution up to date i will be glad.
EDIT :
I will add some details about my test with the module Mickael/request
First Try :
var request = require('request')
var options = {
'url': 'http://api.example.fr/example/1.xml',
'auth': {
'user': 'test',
'pass': 'test',
'sendImmediately': false
}
};
var request = request.get(options, function(error, response, body){
if (!error && response.statusCode == 200){
console.log('body : ' + body)
}
else{
console.log('Code : ' + response.statusCode)
console.log('error : ' + error)
console.log('body : ' + body)
}
});
Second Try :
var request = require('request')
request.get('http://api.example.fr/example/1.xml', function(error, response, body){
if (!error && response.statusCode == 200){
console.log('body : ' + body)
}
else{
console.log('Code : ' + response.statusCode)
console.log('error : ' + error)
console.log('body : ' + body)
}
}).auth('test', 'test', false);
but the return is still the same 401
Here's your example corrected to use request as per it's API.
var options = {
uri: 'http://api.example.fr/example/1.xml',
auth: {
user: 'test',
pass: 'test',
sendImmediately: false
}
};
request(options, function(error, response, body){
if (!error && response.statusCode == 200){
console.log('body : ' + body)
}
else{
console.log('Code : ' + response.statusCode)
console.log('error : ' + error)
console.log('body : ' + body)
}
});
The request chainable style API is a bit confusing (IMHO), but I believe you can make it work that way as well.
The digest auth in the request package seems to be incomplete.
You can try out: https://npmjs.org/package/http-digest-client ,its a pretty decent lightweight implementation for the digest authentication.
If you need to do a digest auth POST with a body message to be sent you can use request in conjunction with http-digest-client. After installing both just open up http-digest-client code under node-modules and replace its use of the http package with the request package api.
Try urllib it will work with simple and disgest auth.
const httpClient = require('urllib');
const url = 'https://site.domain.com/xmlapi/xmlapi';
const options = {
method: 'POST',
rejectUnauthorized: false,
// auth: "username:password" use it if you want simple auth
digestAuth: "username:password",
content: "Hello world. Data can be json or xml.",
headers: {
//'Content-Type': 'application/xml' use it if payload is xml
//'Content-Type': 'application/json' use it if payload is json
'Content-Type': 'application/text'
}
};
const responseHandler = (err, data, res) => {
if (err) {
console.log(err);
}
console.log(res.statusCode);
console.log(res.headers);
console.log(data.toString('utf8'));
}
httpClient.request(url, options, responseHandler);
your sample is work
var request = require('request')
request.get('http://api.example.fr/example/1.xml', function(error, response, body){
if (!error && response.statusCode == 200){
console.log('body : ' + body)
}
else{
console.log('Code : ' + response.statusCode)
console.log('error : ' + error)
console.log('body : ' + body)
}
}).auth('test', 'test', false);