Following scenario:
I got two servers, one server a Website, the other manages a database. The Website sends requests to its server, the request is passed to the backend server and a data set from the database should be returned.
I am using Express on both servers, the one serving the website also has the Request package.
Code on first server:
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:8081/getDataset',
body: "data="+data
},
function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body)
res.send(body)
}
}
)
Code on second server:
getFromEigenschaft (req, res) {
var data = req.body.data
console.log(req.body) //logs {}
//do database stuff with data
return res.status(200).send(dataSet)
}
On the second server req.body is an empty object though. What am I doing wrong?
Found the answer:
The body object can be set to a JSON, just as I want to, but the JSON option must be set to true:
request.post({
headers: {'content-type' : 'application/x-www-form-urlencoded'},
url: 'http://localhost:8081/getDataset',
json: true,
body: data
},
function(error, response, body){
if (!error && response.statusCode == 200) {
console.log(body)
res.send(body)
}
}
)
Related
I am working on a signup page and I am lost trying to set the Authorization Bearer Header. I am using jsonwebtokens to generate the token. I know how to set the header on postman, but how do I set it for the actual route I’m signing up to and be able to use it in my auth middleware for other endpoints ? As postman is just for tests
request.setHeader('Authorization', 'Bearer '+accessToken)
you can set headers inside request in your route. Using request module.
app.post('/test', (req, res, next) => {
console.log("inside the test");
request.post({
url: api_address,
body: JSON.stringify(send),
headers: {
"Content-Type":"application/json",
"Authorization": "Bearer 71D50F9987529"
}
}, function (error, response, body) {
console.log("hiii");
console.log(response.statusCode);
if (!error && response.statusCode == 200) {
// Successful call
var results = JSON.parse(body);
console.log(results) // View Results
}
});
});
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);
});
The following curl request works properly, returning the authentication token as it should
curl POST -s -d "grant_type=password&username=someusername&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token" "someurl"
when the equivalent request in node.js fails
let url = someurl
var dataString = 'grant_type=password&username=somename&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token';
var options = {
url: url,
method: 'POST',
body: dataString,
allow_redirects : true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error)
console.log(body)
}
request(options, callback);
The error is
{"error":"unauthorized","error_description":"An Authentication object was not found in the SecurityContext"}
Which may only be specific to this code. At any rate, what differences (in default parameters presumably or configuration) could explain this difference. Note, the programs fails both with and without allow_redirects option, but redirection should be allowed.
This is node v7.10.0 running on macosx and request 2.81.0
My first assumption would be that you're missing the headers required for your request
let url = someurl
var dataString = 'grant_type=password&username=somename&password=somepassword&client_id=someid&client_secret=somesecret&response_type=token';
var options = {
url: url,
method: 'POST',
body: dataString,
headers: { 'content-type': 'application/x-www-form-urlencoded' },
allow_redirects: true
};
function callback(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
}
console.log(error)
console.log(body)
}
request(options, callback);
If this isn't correct, let me know and i'll resolve the answer
I can't seem to figure out how to do this. I have a repo where I test things and everything should be pretty straight forward, but.
I am using node.js, but that is not much relevant in this problem:
var request = require('request');
var options = {
uri: 'https://api.github.com/repos/capaj/gitup/issues/1/comments',
method: 'POST',
headers: {'User-Agent': 'bot'},
json: {
"body": 'my uber comment'
}
};
request(options, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body);
} else {
//I always get 404
}
});
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);