simple $http.get request with params - javascript

I'm trying to make following http request using angularjs $http service
$http.get('http://myserver:8080/login?', {
params: {username: "John", password: "Doe" },
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}).then(function(response) {
alert('success');
alert(response);
}, function(x) {
alert('err');
});
};
my server is up and runing and I'm getting following firebug console error
So what I'm doing wrong here in sending http request?

Here is an example for send GET request using $http.get with params
$http.get('api/anyApi/get', { params: {name:name}})
As you see, you do not need absolute path and ? param to use.
Also, as jfadich mentioned - do not use GET for such requests.

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

http basic authorization with Flask REST

I am developing a simple REST service in flask.
I have been trying to implement basic authorization.
Whilst, I can pass the username and password from the webpage using manual entry, I can't seem to read them from the header.
Here is my code:
On the server
def test():
if request.authorization and request.authorization.username == '***' and request.authorization.password == '***':
return "Authorized"
else:
return make_response('Authorization failed', 401, {'WWW-Authenticate': 'Basic realm ="Login Required"'})
On the client - using JavaScript
<script>
$(document).ready(function(){
$("#authButton").click(function(){
$.ajax({
xhrFields: {
withCredentials: true
},
headers: {
'Authorization': "Basic " + btoa("***:***")
},
url: "********:5001/",
type: 'GET',
success: function(){
console.log("success");
},
error: function (){
console.log("error");
},
});
});
});
</script
>
I have also tried the Javascript code without the xhr fields section, but for neither do I get anything returned at all.
If I don't send the headers from the client it works and simply asks for manual input of the username and password.
All I'm trying to do is authenticate from the header.
Any pointers would be very gratefully received.

Nodejs request post with body include api key

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")

Bad request while trying to access Github's v4 API with graphql.js

I am trying to retrieve some data from Github's GraphQL API using graphql.js library.
var graph = graphql("https://api.github.com/graphql", {
method: "POST",
headers: {
"Authorization": "Bearer <my-token-here>",
"Content-Type": "application/json"
},
fragments: {
rateLimitInfo: "on RateLimit {cost,remaining,resetAt}"
}
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
id
}
}
`,{
name: "freeCodeCamp",
owner: "freeCodeCamp"
}).then(function(response){
console.log(response);
}).catch(function(error){
console.log(error);
});
My promise is not being fulfilled and always failing. I am getting an HTTP response with code 400 (Bad Request) and the error argument of the catch function reads:
{
message: "Problems parsing JSON",
documentation_url: "https://developer.github.com/v3"
}
I have already tried passing the variables as JSON, like so:
{
"name": "freeCodeCamp",
"owner": "freeCodeCamp"
}
But it didn't help. I got the same bad request.
Looking at the Network tab of Chrome's inspector I see what the request payload is. Adding it here in case it give any clues or help.
query=query%20repo(%24name%3A%20String!%2C%20%24owner%3A%20String!)%7Brepository(name%3A%24name%2C%20owner%3A%24owner)%7Bid%7D%7D&variables=%7B%22name%22%3A%22freeCodeCamp%22%2C%22owner%22%3A%22freeCodeCamp%22%7D
What am I doing wrong?
The default behaviour of graphql.js is to send the body in form-url-encoded format whereas Github GraphQL api accepts only JSON format. From graphql.js readme :
As default, GraphQL.js makes a POST request. But you can change the
behavior by setting asJSON.
var graph = graphql("http://localhost:3000/graphql", {
asJSON: true
});
You can see the difference here
The following will work as expected :
var graph = graphql("https://api.github.com/graphql", {
headers: {
"Authorization": "Bearer YOUR_ACCESS_TOKEN"
},
asJSON: true
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
id
}
}
`, {
name: "freeCodeCamp",
owner: "freeCodeCamp"
}).then(function(response) {
console.log(response);
}).catch(function(error) {
console.log(error);
});

$http.jsonp - unexpected token '<'

I'm able to get a response from the request but the .then() part of my code doesn't fire. What am I doing wrong?
window.distance24Result = function(data){ alert(data.distance); };
$http.jsonp("http://www.distance24.org/route.jsonp?stops="+city+"|"+country,{data:'jsonp',
jsonpCallbackParam: 'distance24Result'
})
.then(function(data){console.log(data);});
If you have a look at the docs, you'll have to pass jsonp as the jsonpCallbackParam so that Angular uses the correct request url. It's the name of the GET parameter, not the name of the callback function. Also, the path is route.json not route.jsonp.
$http.jsonp("http://www.distance24.org/route.json?stops="+city+"|"+country, {
jsonpCallbackParam: 'jsonp'
}).then(function(data) {
console.log(data);
alert(data.distance);
});
Alternatively, you can also use
$http.jsonp("http://www.distance24.org/route.json", {
params: {stops: city+"|"+country},
jsonpCallbackParam: 'jsonp'
})
Before Angular v1.6, there was no jsonpCallbackParam config value. Instead you'd use
$http.jsonp("http://www.distance24.org/route.json?jsonp=JSON_CALLBACK&stops="+city+"|"+country)
or
$http.jsonp("http://www.distance24.org/route.json", {params: {
"stops": city+"|"+country,
"jsonp": "JSON_CALLBACK"
}})

Categories