Nodejs request post with body include api key - javascript

I have been trying about a week but I couldn't make a post request to get a result.
I tried a bunch of middlewares (exp: 'request', 'axios', 'reqclient','superagent etc..) but I couldn't make it.
Please provide me a simple post request with sending API key and body.
I also read all the documentation.
Please check below to see what I want :
*Authentication API key required.
*O-Auth Scopes trades
*Input One of: user_id + token or user_url is required.
here is my one of try :
const request = require('request-promise')
const options = {
method: 'POST',
uri: 'api-site.com/Offer/v1/',
headers: {
'User-Agent': 'Request-Promise',
'Authorization': 'Basic 123123asdasd123123'
},
body: {
user_url: "site.com/user/user1234123",
otherparams: "parameter"
},
json: true
};
request(options)
.then(function (response) {
Console.log(response);
})
.catch(function (err) {
console.log('Error ', err.message);
});
I am getting this output :
Error : 401 - {"status":401,"time":1540458426,"message":"API Key Required"}
I tried some other request post middle-wares and played with content-type (application/json. dataForm, x-www-form-urlencoded) or
changed the location of my API key from header to body or
tried my API key inside of auth{authorization: "API Key"}
tried much more.
the result didn't change. I got the same output or errors.
EDIT :
this is the link that I am trying to do but got stack :
check here

Solved !
Everything works great. Problem was I needed to send my API Key base64 string.
Buffer.from("your_api_key_value" + ":", "ascii").toString("base64")

Related

Postman pre-request to get token doesn't work

At this time I can perform succesfully my Postman request to get my token. I'm using these parameters :
-Basic Authorization in the headers
-and this body
-
Now I would like to get this request as a pre-request script (and use an environment variable for the token).
Here is the script :
pm.sendRequest({
url: 'http://localhost:8084/oauth/token',
method: 'POST',
header: {
'Authorization':'Basic Y2xpZW50OnBhc3N3b3Jk',
'content-type': 'application/x-www-form-urlencoded'
},
data:{
'password':'secret',
'username':'admin',
'grant_type':'password'
}
}, (err, res) => pm.environment.set("token", res.json().access_token));
It doesn't work with the response : Full authentication is required to access this resource.
What is wrong?
Thanks
You could change the data section to something like this?
body:{
mode:"urlencoded",
urlencoded:[
{
key:"grant_type",
value:"password"
},
{
key:"username",
value:"admin"
},
{
key:"password",
value:"secret"
}
]
}
A great resource for pm.sendRequest() examples can be found here

JS: axios POST with large nested object and form-data

I am to post an Axios request because using get results in a 414 error.
Here's the object:
rows= {
0 : {
"name":"Thor",
"status":"active",
"email":"somuchlightning#kaboom.io",
},
1 : {
"name":"Mesa",
"status":"active",
"email":"big-mesa#tundra.com",
},
2 : {
"name":"Jesper",
"status":"stdby",
"email":"jes#slap.net,
},
}
This is just a sample of the object's format. There is 400+ elements in the real one, thus post instead of get. I am having trouble properly building the form-data on this one. Here's what I have:
let data = new FormData();
Object.keys(rows).forEach(key => data.append(key, rows[key])); // <--- this doesn't do
data.set('target', target); // <---- this comes through just fine
axios({
method: 'post',
url: 'byGrabthorsHammer.php',
data: data,
headers: {'Content-Type': 'multipart/form-data'}
}).then(function(response) {
if (response.error) {
console.log('failed to send list to target');
console.log(response);
} else {
console.log('response: ');
console.log(response);
}
});
What comes through is just [Object][Object]' when ivar_dump($_POST);`. This is not what I want. How could I rewrite this properly so I get the data to the other side (like GET...).
Yow bro, POST Are for inserting new stuff, instead of doing a post you need a patch
axios.patch it is basically the same. And it won’t fix your issue.
To fix the issue you need to set the Content-Type to application/json, then on yow
axios.post(url, data: JSON.stringify(bigObject))
.then(Rea=>Rea)
You could try stringifying the data. JSON.stringify(data)

couchDB 401 error

I have a couchDB database called "guestbook". I first used the code below to add the a user to the "_users" database:
$scope.submit = function(){
var url = "https://sub.iriscouch.com/_users/org.couchdb.user:" + $scope.name;
console.log(url);
$http({
url: url,
method: "PUT",
data: {name : $scope.name,
password: $scope.pass,
roles: [],
type: "user"
},
withCredentials: true,
headers: {"Authorization": auth_hash(adminUsername, adminPass)}
})
.success(function(data, status, headers, config){
console.log(headers);
console.log(config);
});
}
Once the user was added to _users I used Futon to add that user as member to my "guestbook" _security document.
After that I tried to used that username and password (that was added as a member to "guestbook" _security) to get all the documents in the "guestbook" database. See code below:
$scope.login = function(){
var url = "https://sub.iriscouch.com/guestbook/_all_docs";
$http({
url: url,
method: 'GET',
params: {
include_docs: true,
},
withCredentials: true,
headers: {"Authorization": auth_hash($scope.uname, $scope.upass)}
})
.success(function(data, status, headers, config){
$scope.book = data.rows;
console.log($scope.book);
});
}
function auth_hash(username, password)
{
return "Basic" +btoa(username + ":" + password);
}
But everytime I tired access the "_all_docs" I get a 401 unauthorised error. The username I am using to access has been added as a member into the _security documents of the guestbook database.
Can anyone help. What am I doing wrong.
Do you have added the user name w/o the org.couchdb.user prefix to the _security object?
I can easily understand your code but didn't see a obviously mistake. I would recommend you test your API calls with Postman (Chrome App) or similar to know whether the problem is client- or server-side caused.
401 indicates Couch is unable to log in your user rather than it's not allowing them access to the database.
Might be a copy/paste error in writing the code example, but it looks like your line:
return "Basic" +btoa(username + ":" + password);
Is missing a space between Basic and your hash in the returned string:
return "Basic " +btoa(username + ":" + password);
This will mean that your Authorization header isn't correct.
However, your first code block appears to use the same function successfully, so I'm clutching at straws.

Unsupported grant type error when requesting access_token on Spotify API with Meteor HTTP

I've been unable to solve a problem while requesting an access_token on Spotify API with Meteor HTTP. Indeed, when I make a POST call to the Spotify https://accounts.spotify.com/api/token. I get the following response :
{"statusCode":400,"content":"{\"error\":\"unsupported_grant_type\",\"error_description\":\"grant_type must be client_credentials, authorization_code or refresh_token\"}"
I think this may have something to do with the Content-Type header and the encoding of the BODY parameter but I haven't been able to solve this issue. I tried to use both data and params and none of these worked.
Here is my code :
HTTP.post("https://accounts.spotify.com/api/token", {
data: {
grant_type : "authorization_code",
code : authCode,
redirect_uri : Router.routes['redirect_spotify'].url()
},
headers: {
'Authorization' : "Basic " + CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse("xxxx:yyyyy")),
'Content-Type':'application/x-www-form-urlencoded'
}
}, function(error, result) {
console.log("POST made with data : %j", result);
if (error){
Registrations.remove({userId : this.userId });
return;
}
Registrations.update({
userId : this.userId },
{$set : {
state: "Done",
accessToken: result.access_token,
//TODO expires
refreshToken: result.refresh_token
}},
{ upsert : true}
);
});
Thank you all in advance :) Love Meteor
You need to use params instead of data. Thus, your code would be:
HTTP.post("https://accounts.spotify.com/api/token", {
params: {
grant_type : "authorization_code",
code : authCode,
redirect_uri : Router.routes['redirect_spotify'].url()
},
headers: {
'Authorization' : "Basic " + CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse("xxxx:yyyyy")),
'Content-Type':'application/x-www-form-urlencoded'
}
}, function(error, result) {
...
});
Sending data in the format query params in the request body also works when the method is POST.
For example:
Sending the data values, name = 'Tommy' and age = 26 in the request body as
name=Tommy&age=26

jQuery.ajax to $http

I used this function
jQuery.ajax({
type: 'POST',
url: urlSubmit,
timeout: 5000,
dataType: 'text',
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
"success": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX success :) - statut " + textStatus);
$timeout(successMailZR_alerte, 3000);
},
"error": function (jqXHR, textStatus, errorThrown) {
console.log("AJAX fail :/ - statut " + textStatus);
$timeout(errorMailZR_alerte, 3000);
}
});
Whats the code is doing : code POST to a php script who send an email.
but, since i rewrited my code in a complete angularjs app, i do it like this :
$http({
method: 'POST',
url: urlSubmit,
timeout: 5000,
cache: false,
data: {
date : dataDate,
url : dataUrl,
domaine : dataDomaine,
email : dataEmail,
destinataire : dataDestinataire,
msg : dataMsg
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
responseType: 'text',
}).
success(function(data, status, headers, config) {
console.log("AJAX success :) - statut " + status);
$timeout(successMailZR_alerte, 3000);
}).
error(function(data, status, headers, config) {
console.log("AJAX fail :/ - statut " + status);
$timeout(errorMailZR_alerte, 3000);
});
Problem is : with $http, i have a success 200 but nothing is posted and i have no return in my email. What's the problem ?
The problem is that jQuery's POST does send your data as form data (e.g. key-value pairs) (https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Forms/Sending_and_retrieving_form_data) whereas AngularJS sends your data in the request payload. For a difference between the two see the following SO question: What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab
In order to make your angular script works with your server you have to convert your data to a URL encoded string as described here: How can I post data as form data instead of a request payload?. Simply setting headers: {'Content-Type': 'application/x-www-form-urlencoded'} is not enough.
A different approach would be to adapt the back-end of your application to parse the message payload instead of the form data parameters.
To understand this one need to understand the request headers set by angular and jquery, There are differences with the headers like when request is post by jQuery then header might look like this:
POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded // default header set by jQuery
foo=bar&name=John
You can see this in form data in the request made in the browser, if you use chrome then you can see this in chrome inspector at network tab, if you click the request then you can see the form data and content headers set by the jQuery.
On the other side with angular js $http service, when a request is made then you can find these:
POST /some-path HTTP/1.1
Content-Type: application/json // default header set by angular
{ "foo" : "bar", "name" : "John" }
The real difference is this you have a request payload not usual form data which is used by jQuery. so you need to do something extra at the server side like below.
Use this:
$data = json_decode(file_get_contents("php://input"));
echo $data->date;
// and all other params you have sent
This is due to its default headers
Accept: application/json, text/plain, * / *
Content-Type: application/json
and jQuery unlikely have something else:
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

Categories