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?
Related
const data = new FormData();
data.append("image", uploadedimage);
console.log(data);
axios
.post("https://api.imgur.com/3/image/", data, {
headers: {
Authorization: `Client-ID ${apiKey}`,
},
})
.then((res) => {
console.log(res);
});
I have this code set up inside of my react app. I can't figure out why I keep getting this authentication error.
{
"data": {
"error": "Authentication required",
"request": "/3/image/",
"method": "GET"
},
"success": false,
"status": 401
}
I know my API-Key and uploaded image is good but for some reason this code is not getting through. Any help would be greatly appreciated. I am look at this in the imgur api docs,
curl --location --request POST 'https://api.imgur.com/3/image' \
--header 'Authorization: Client-ID {{clientId}}' \
--form 'image=R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
I found this in the Axios docs here, not sure if it'll help or not.
enter link description here
// Set config defaults when creating the instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
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.
Currently I have an axios post request that works fine for sending the data to Spring Boot backend. But it just wraps single list of data to json and sends it as requested body:
Example:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
}).then(response=> console.log("repsonse", response.status)) // is 201
}
And it receives it on backend:
#RequestMapping(path = "/receiveData", method = RequestMethod.POST)
public ResponseEntity<Void> receiveData(#RequestBody Collection<ActivePOJO> activitePOJOS) {
//DO WORK WITH activePOJOS DATA
return new ResponseEntity<>(HttpStatus.CREATED);
}
However, apart from that information, I also need to send some other info like user.id (as example), so I need my backend to receive something like this:
public ResponseEntity<Void> receiveData(#RequestBody Collection<ActivitePOJO> activePOJOS, Long userID)
But I don't know which way should I prepare axios post for something like that. Should I use params instead of body?
You can use params and body together in a request with axios. To send userID as a param:
sendAllData(data) {
return axios.post(API_URL + "receiveData", JSON.stringify(data),
{ headers: { "Content-Type": "application/json; charset=UTF-8" },
params: { userID: 1 }, //Add userID as a param
}).then(response=> console.log("repsonse", response.status)) // is 201
And receive userID in controller with #RequestParam annotation:
public ResponseEntity<Void> receiveData(#RequestBody Collection<ActivitePOJO> activePOJOS, #RequestParam("userID") Long userID){
// here you can access userID value sent from axios
}
The third parameter is config and you can pass params to it along with header as a separate key. Refer this. https://github.com/axios/axios#axiosposturl-data-config
sendAllData(data) {
return axios
.post(API_URL + 'receiveData', JSON.stringify(data), {
headers: { 'Content-Type': 'application/json; charset=UTF-8' },
params: { userId: 2 },
})
.then((response) => console.log('response', response.status));
} // is 201
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()) }
);
I am trying to convert below sample code in angular request.
https://documentation.mailgun.com/user_manual.html#sending-via-api
curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages \
-F from='Excited User <mailgun#YOUR_DOMAIN_NAME>' \
-F to=YOU#YOUR_DOMAIN_NAME \
-F to=bar#example.com \
-F subject='Hello' \
-F text='Testing some Mailgun awesomness!'
I have tried below with Authorization headers which still comes back with Unauthorized error. I see request header has authorization field set with value.
What am I doing wrong?
var url = "https://api.mailgun.net/v3/sandboxXXXXXXXXXXXXXXXXX.mailgun.org/messages";
var dataFields = {
to: "verified recepient",
subject: "subject",
text: "text",
from: "postmaster address of sandbox domain"
}
var req = {
method : 'POST',
url: url,
headers : {
'Authorization' : 'Basic api:key-XXXXXXXXXXXXXXXX'
},
data: dataFields
}
$http(req).then(function(data){
console.log(data);
}, function(data){
console.log(data);
})
Finally got it working from local machine - collective information from different post and using this plugin - https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi - I was able to make it work. So what does this plugin does? can I do this in my post request?
Without that it gives me error
XMLHttpRequest cannot load https://api.mailgun.net/v3/sandboxXXXXXXXXXX.mailgun.org/messages. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
var url = "https://api.mailgun.net/v3/sandboxXXXXXXXXXXXXXXX.mailgun.org/messages";
var dataJSON = {
from: "postmaster#sandboxXXXXXXXXXXXXXXX.mailgun.org",
to: "registered recepient",
subject: "Subject text",
text: "Body text",
multipart: true
}
var req = {
method : 'POST',
url: url,
headers : {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + $base64.encode('api:key-XXXXXXXXXXXXX')
},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: dataJSON
}
$http(req).then(function(data){
console.log(data);
}, function(data){
console.log(data);
})
Things which I was missing.
Multipart
context type
encodedURIComponent - for parameters
base64 encoded api key
Try to add
username: 'api',
password: 'yourapikey',
in your header request