Make a js request with 2 methods POST and PUT - angularjs

I got api for creating cats with authorisation token
curl -X POST -H "Authorization: JWT <dat_token>" -X PUT -H "Content-Type: application/json" -d '{"name":"SuperApi2","breed":"Bite"}' http://127.0.0.1:8000/cats/api/
how to write request in AngularJs for this operation? It has 2 methods POST and PUT
I tried to play with something like this but it does not work
var req = {
method: 'POST',
url:'http://127.0.0.1:8000/cats/api/',
headers: {
'Authorization':'<data_token>',
'Content-Type': 'application/json'
},
data: {"name":"AngularJs","breed":"Bite"}
};
$http(req).then(
function(qwe) { console.log(qwe) },
function(error) { alert(error.toSource()) }
);

Ok, this operation does not really need POST method, only put
var req = {
method: 'PUT',
url:'http://127.0.0.1:8000/cats/api/',
headers: {
'Authorization':'<data_token>',
'Content-Type': 'application/json'
},
data: {"name":"AngularJs","breed":"Bite"}
};
$http(req).then(
function(qwe) { console.log(qwe) },
function(error) { alert(error.toSource()) }
);

Related

Napster API Auth - BAD Request / Unauthorized

I am coding in Reactjs and trying to Auth/Outh into the Napster Web API, followed the information on this page: https://developer.napster.com/api/v2.2#authentication
A sample of my current code:
const API_KEY = 'OWIxMjhlY2MtOTA3Yi00NWJiLThiYTktODc3OTNiYTQ4MGU4';
const API_KEY_SECRET = 'OWIxMjhlY2MtOTA3Yi00NWJiLThiYTktODc3OTNiYTQ4MGU4';
url: 'https://api.napster.com/oauth/access_token',
method: 'post',
params: {
client_id: API_KEY,
client_secret: API_KEY_SECRET
},
headers: {
'Accept':'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + (new Buffer(API_KEY + ':' + API_KEY_SECRET).toString('base64'))
},
data: querystring.stringify({ grant_type: 'authorization_code' })
Response Payload:
{"code":"UnauthorizedError","message":"Authentication code not valid"}
{"code":"BadRequestError","message":"Invalid grant_type parameter"}
According to the documentation and sample below....
curl -v -X POST -d "client_id={api_key}&client_secret={api_secret}&response_type=code&grant_type=authorization_code&redirect_uri={redirect_uri}&code={temporary_code}" "https://api.napster.com/oauth/access_token"
...You don't need to send Authorization headers. It's a normal form post with all the parameters. So If you include the rest of the parameters along with client_id : API_KEY... it should do the trick.

Mocking Postman GET request using axios is giving different results

I am trying to mock up the following request , which I have in Postman, into Axios:
in terms of cURL:
curl --location --request GET 'http://url' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer blablabla' \
--data-raw '{
"category":{
"value": "category1"
}
}'
in terms of Nodejs-Request:
var request = require('request');
var options = {
'method': 'GET',
'url': 'http://url',
'headers': {
'Content-Type': 'application/json',
'Authorization': 'Bearer blablabla'
},
body: JSON.stringify({"category":{"value":"category1"}})
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Note: the first two codes had been generated by Postman.
When I send this request via Postman, and dump the request parametes on the server, I will get the following result:
array:1 [
"category" => array:1 [
"value" => "category1"
]
]
in terms of Axios:
var config = {
params: {
category:
{
value: 'category1'
}
},
headers: {
'Authorization': 'Bearer blablabla'
}
};
return Axios.get('http://url', config);
While dumping the parameters sent via Axios will generate the following result:
array:1 [
"category" => "{"value":"category1"}"
]
Note the difference between the two results, where the value of the category in the first result is an array, but its a string in the second !!
How I can fix my Axios request to get the same result as same as the Postman request?

Convert this CURL Command to Javascript fetch()

I have a problem, I'm trying to access an API via javascript fetch().
In their documentation, they only have the curl guide
curl https://test.com/form/{form_id}/data \
-u apikey:'some-key'
Can you guys help me convert it to javascript fetch?
I tested the code below but the browser console says error 401 now I don't think I did put the apikey on the right location.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
apikey : 'some-ley',
'Content-Type': 'application/json'
}
})
Thanks in advance. :)
I think what is failing there is the type of header you are sending in fetch.
The -u option in curl translates to the "authorization" header in fetch. So it would be something like this.
fetch(https://test.com/form/371489/data', {
method: 'GET',
headers: {
'Accept': 'application/json',
'authorization' : 'Basic apikey:some-key',
'Content-Type': 'application/json'
}
})
Although probably you would need to base64 encode the apikey:some-key portion before sending it.
Try this format:
fetch("https://test.com/form/{form_id}/data", {
headers: {
Authorization: "apikey ABCDEFGHIJK.."
}
})
Try these awesome online cURL converters!
Here is the output when you paste the cURL command and select the Javascript target:
fetch('https://test.com/form/371489/data', {
headers: {
'Authorization': 'Basic ' + btoa('apikey:some-key')
}
});

Http request in angular send undefine values

** It turns out that the problem was at the server **
I'm trying to excute HTTP post request (from my angular client) to my server (node express). The server recive the request but the data is undefined.
Already tried to make this req by postman and it worked perfect there.
var req = {
method: 'POST',
url: _url +'/login',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: { user: 'someUser', password :'somePass' }
}
$http(req)
.then(function success(res){
...
}, function error(res){
...
});
You are sending JSON data and sending the header of x-www-form-urlencoded.
Change the content type to "application/json"
Like:
headers: {
'Content-Type': 'application/json'
}

Basic authenticiation in $http Get request

I am trying to access a REST API service with basic authenticiation.
This works perfectly as a curl request:
curl -D- -X GET -H "Authorization: Basic eW**********0NQ==" -H "Content-Type: application/json" "https://api.domain.com/api/users/email/first.last#domain.com"
In angular, I tried this and it does not seem to work as I get a 501 error...
var _url = "https://api.domain.com/api/users/email/first.last#domain.com";
var _authdata = Base64.encode('MyUsername' + ':' + 'MyPassword');
var _headers = {
'Authorization': 'Basic eWd***********0NQ==',
'Content-Type': 'application/json'
};
$http({
method: 'GET',
url: _url,
headers: _headers
}).then(function(request) {
console.log('request');
});
I am trying to understand why this isn't working out properly. CORS are not the problem...
Any suggestions ?
Base64.encode is not understandable by angular-js either you can use javascript "btao" and "atob" or you can include the base64 through npm
Maybe the following code snippet will help you.
var _url = "https://api.domain.com/api/users/email/first.last#domain.com";
var _authdata = btoa('MyUsername' + ':' + 'MyPassword');
var _headers = {
'Authorization': 'Basic' + _authdata,
'Content-Type': 'application/json'
};
$http({
method: 'GET',
url: _url,
json: true,
headers: _headers
}).then(function(request) {
console.log('request');
});
or you can include the Angular-base64 dependency using npm:
https://www.npmjs.com/package/angular-base64

Resources