Hello I have tried to use the instagram api to get a connection token. I first tested it on postman and this is what I did:
I used this link to make a request post to the instagram api:
https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode
The api gives me an error: Missing required field client_id
But when I set the content type to x-www-form-urlencoded everything works fine on postman.
So I tried to do the same thing in javascript with the node module request. I tried to do the same thing as on postman with the module but it does not work... Here is my code:
request(`https://api.instagram.com/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=` + code, {
method: 'POST',
headers: {"Content-Type": "x-www-form-urlencoded"}
}, (error, response, body) => {
console.log('body:', body)
})
As per MDN, the content type should be application/x-www-form-urlencoded
https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST
Update:
You should read the node doc : https://nodejs.dev/learn/making-http-requests-with-nodejs
Get method:
const https = require('https');
const options = {
hostname: 'api.instagram.com',
path: '/oauth/access_token?client_id=clientid&client_secret=clientsecret&grant_type=authorization_code&redirect_uri=https://mysite/&code=thecode',
method: 'GET',
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
}
};
const req = https.request(options, (res) => {
// ...
});
Post method:
var headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Accept": "Accept-Encoding"
};
var options = {
url: 'https://api.instagram.com/oauth/access_token',
method: 'POST',
headers: headers
};
var form = {
grant_type:'urn:ietf:params:oauth:grant-type:jwt-bearer',
client_id: 'id',
client_secret: 'secret'
redirect_uri : 'https://mysite/&code=thecode'
};
var request = https.request(options, function(response) {
// do stuff
});
request.write(querystring.stringify(form));
request.end();
Related
I use the following code using request which works as expected, got http response 200
var request = require('request');
var auth
var options = {
'method': 'POST',
'url': 'https://oauth2.k.de.com/oauth2/token',
'headers': {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
'grant_type': 'client_credentials',
'scope': 'app:read'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
let body = JSON.parse(response.body);
….
Now I need to convert it to axios as request been deprecated but it’s not working for me ( I got http 400 response )
const axios = require('axios').default;
axios({
method: 'post',
'url': 'https://oauth2.k.de.com/oauth2/token',
data: {
'grant_type': 'client_credentials',
'scope': 'app:read'
},
headers: {
'Accept': 'application/json',
'Authorization': 'Basic NGViMTE2ODctZTNjNi00NDUyLTgwNjgtMzhiOjJDR2lJd0hxOFFx==',
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function (response: any) {
console.log("Head With Authentication :" + response);
}).catch(function (error: any) {
console.log("Post Error : " + error);
});
Any idea why with request library with the exact same data it works (http response 200) and in axios I got 400 ?
In request I put the grant_type etc in form and in axios in data, this is the only diffrencace I see, any idea?
This is the error I got
Request failed with status code 400
Should I use other rest libary if it cannot be done via axios ?
This is a bug, you might want to check this: https://github.com/axios/axios/issues/362
The problem is, because of axios interceptors, your Content-Type header is disappearing. If you have access and can change the backend, you can make it work with another header and set it on your client code. Otherwise if your code is working in a browser, you can try using URLSearchParams as suggested here.
I mean, i'm trying to make the most simple upload ever, with the following code:
var http = require('http');
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: form.getHeaders()
});
form.pipe(request);
request.on('response', function(res) {
console.log(res.statusCode);
});
The point is, if i make a post like this, what it'll post exacly?
Does i need to put at least one header parameter or this create some kind of template?
If i need to put at least one parameter, i would put it into the form.getHeaders"()"?
Through headers you should send HTTP headers of the request as an object
Example code:
var request = http.request({
method: 'post',
host: 'https://www.ws-ti.4bank.com',
path: '/img/create_file',
headers: {
'Accept': 'text/html',
}
});
full list of the header can be found here
You can send data as JSON with the request as follows:
const data = JSON.stringify({
text: 'Hello World'
});
request.write(data);
request.end();
I am trying to do query to find a account using rest services of the target application name hexion.
When I am running it is giving Invalid uri error.
The url that I tested in postman is like below
https://ekaa-dev1.fa.us6.oraclecloud.com/crmRestApi/resources/11.13.18.05/accounts?q=OrganizationName = Hexion
and in postman I am getting response too.
But I feel somewhere in my code I am doing some syntax error but not able to find that
//nodejs v4.2.6
console.log("Hello, World!");
var Request = require("request");
var serviceUserName="msonawane#gmail.com";
var password="Welcome01";
var personalDataURL="https://ekaa-dev1.fa.us6.oraclecloud.com/crmRestApi/resources/11.13.18.05/accounts";
var option1 = {
uri: personalDataURL,
qs: {
q:{OrganizationName:"Hexion"}
},
headers: {
"Authorization" : auth,
"Content-Type": 'application/json',
"Accept":'application/json'
}
};
var auth = `Basic ` + new Buffer(serviceUserName+`:`+password).toString(`base64`);
Request.get(option1, { json: true },
(error, response, body) => {
console.log(response);
//console.log(response.url);
if (error) { return console.log(body,error); }
console.log(body.url);
console.log(body.explanation);
});
I expect it to return response after successful get
Please let me know error, I have changed the auth credentials so once you find anything to be corrected let me for the above code, I will try with right credentials and update you
request.get method expects first parameter as url, but you are passing options1 obj, it couldn't find url hence it is giving error "Invalid uri /".
You can append query parameter to url OR use querystring npm
var personalDataURL= "https://ekaa-dev1.fa.us6.oraclecloud.com/crmRestApi/resources/11.13.18.05/accounts?q=OrganizationName=Hexion"
request({
headers: {
"Authorization" : auth,
"Content-Type": 'application/json',
"Accept":'application/json'
},
uri: personalDataURL,
method: 'GET'
}, function (err, res, body) {
//it works!
});
For more details, refer request
I have an application where we are generating a JWT token and passing that token in Header in the next api call.As a response of that, I should get a key.I am able to see the response through postman.I am using ReactJS in Front End and trying to achieve the same by passing the JWT token in Header while doing the api call but facing some issues.
My code-
getKey() {
let postData = {
vin: "5678",
id: "abc12",
};
axios({
method: "post",
url: "http://localhost:8080/generateKey",
headers: {
"Content-Type": "application/json"
},
data: postData
})
.then(function(response) {
setKey(response.data.key);
})
.catch(function(error) {
console.log(error);
getKeyError();
});
}
memberAuth() {
var self = this;
axios({
method: "GET",
url: "http://localhost:8080/authenticateMember",
headers: {
"Content-Type": "application/json",
"Authorization": localStorage.setItem()
},
data: {
"id":"xyzzy",
"password":"abc"
}
})
.then(function(response) {
//to do
}
I am trying to save the generated token (valid for 30mins) in a localStorage/SessionStorage but not sure if this is the right way. Can someone tell me where am I going wrong.
Create instance of your axios,
const agent = axios.create({
baseURL: config.api_url,
transformRequest: [transformRequest],
transformResponse: [transformResponse],
headers: { 'Content-Type': 'application/vnd.api+json' },
});
And then call this function to set headers dynamically
agent.defaults.headers.common['Authorization'] = `JWT ${localStorage.getItem('token')}`;
Then call methods of your axios instance to make API calls
agent.get(`${endpoint}search`, { params }),
agent.post(`${endpoint}search`, JSON.stringify(body)),
I'm trying to build a request for uClassify API from Node. I can't figure out what is wrong with the code I've written:
const req = JSON.stringify('Hello, my love!');
const options = {
body: req,
method: 'POST',
url: 'https://api.uclassify.com/v1/uClassify/Sentiment/classify',
headers: {
'Content-Type': 'application/json',
Authorization: 'MyKey'
}
};
request(options, (error, response, body) => {
if (!error) {
callback(response);
}
});
I get the following response:
statusCode: 400,
body: "{"statusCode":400,
"message": "Error converting value \"Hello, my love!\" to
type 'UClassify.RestClient.TextPayload'. Path '', line 1, position 17."}"
}"
There's no clear instruction for JS in the documentation, and I wonder whether I've implemented their example in cURL correctly in my request code.
url -X POST -H "Authorization:Token YOUR_READ_API_KEY_HERE" -H
"Content-Type: application/json" --data "{\"texts\":[\"I am so happy
today\"]}" https://api.uclassify.com/v1/uClassify/Sentiment/classify
In your Node.js code your body is incorrect (but in your cURL you use the correct body). uClassify expects the object with property texts.
Change the body in your node.js code so:
const req = JSON.stringify({ texts: ['Hello, my love!'] });
const options = {
body: req,
method: 'POST',
url: 'https://api.uclassify.com/v1/uClassify/Sentiment/classify',
headers: {
'Content-Type': 'application/json',
Authorization: 'MyKey'
}
};
request(options, (error, response, body) => {
if (!error) {
callback(response);
}
});