Make request to uClassify API via Node request - javascript

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);
}
});

Related

Instagram API Access Token Request Javascript

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();

how to GET responses when data post to URL in nodejs as req.body.url

I want to get data from the URL I have entered as req.body.url inside the body of postman collection tool
how do I get the response
I have a key as URL and the value as live URL see the below screenshot
const options = {
url: req.body.url,
method: 'post',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
request(options, function(err, res, body) {
let json = JSON.parse(options);
res.send(json);
console.log(json);
});
tried above code but it does reads the URL and does not provide the data as response
use this :
var request = require('request');
const options = {
url: req.body.url,
method: 'post',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'my-reddit-client'
}
};
request(options, function (error, response) {
if (error) throw new Error(error);
console.log(response.body);
});
Note that request is asynchronous

using http with axios return 400 with request it works

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.

POST with custom headers using Request Library

I am trying to make a POST request to Expo's servers using the request library for JS.
Expo requires that certain headers be added, and so I went ahead and added them in a dictionary called headers.
expoPushURL = "https://exp.host/--/api/v2/push/send";
headers = {
"accept": "application/json",
"accept-encoding": "gzip, deflate",
"content-type": "application/json"
};
data = JSON.stringify({
"to": "ExponentPushToken[myDeviceToken]",
"sound": "default",
"title": "hello",
"body": "Hello world!"
});
options = {
url: expoPushURL,
headers: headers,
method: "POST",
body: data,
json: true
};
request(options, function (error, response, body) {
console.log("Response from request: ",response);
console.log("Error from request: ", error);
});
The callback is returning an undefined object. The request module has been imported without any problems. What am I doing wrong?
I am getting this error message:
Error from request: { Error: getaddrinfo ENOTFOUND exp.host exp.host:443
at errnoException (dns.js:28:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:76:26)
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'exp.host',
host: 'exp.host',
port: 443 }
These "settings" or parameters work perfectly fine when I use curl or Python's requests library, but I need this solution to be in JS. With that said, I am sure that means there is something wrong with my code.
EDIT: The related curl would look like this:
curl -H "Content-Type: application/json" -X POST https://exp.host/--/api/v2/push/send -d '{
"to": "ExponentPushToken[xxxxxxxxxxxxxxxxxxxxxx]",
"title":"hello",
"body": "world"
}'
You do not have problem with headers, they are working correctly, something else is missing. What is your curl?
I have run your code against my dummy server, which returns in body all interesting values that he accepted. With this code
const expoPushURL = "http://localhost:3099";
const headers = {
"accept": "application/json",
"accept-encoding": "gzip, deflate",
"content-type": "application/json"
};
const data = JSON.stringify({
"to": "ExponentPushToken[myDeviceToken]",
"sound": "default",
"title": "hello",
"body": "Hello world!"
});
const options = {
url: expoPushURL,
headers: headers,
method: "POST",
body: data,
json: true
};
import * as request from 'request';
request(options, function (error, response, body) {
console.log(body.received);
});
I got this response
{ body: '"{\\"to\\":\\"ExponentPushToken[myDeviceToken]\\",\\"sound\\":\\"default\\",\\"title\\":\\"hello\\",\\"body\\":\\"Hello world!\\"}"',
method: 'POST',
headers:
{ accept: 'application/json',
'accept-encoding': 'gzip, deflate',
'content-type': 'application/json',
host: 'localhost:3099',
'content-length': '115',
connection: 'close' },
url: '/' }
If someone would be just interested, the server I am using is having this code
const http = require('http');
const _ = require('lodash');
http.createServer((request, response) => {
const { headers, method, url } = request;
let body = [];
request.on('error', (err) => {
console.error(err);
}).on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
let bodyToSend = JSON.stringify({
alwaysHere: 'Always here',
received: {
body,
method,
headers,
url,
}
});
if (body) {
body = JSON.parse(body);
if (body && _.isObject(body.control)) {
const control = body.control;
if (_.isNumber(control.statusCode)) {
response.statusCode = control.statusCode;
}
if (_.isArray(control.headers)) {
control.headers.forEach(header => {
response.setHeader(header.name, header.value);
});
}
if (_.isString(control.body)) {
bodyToSend = control.body;
}
}
}
if (!response.hasHeader('content-type')) {
response.setHeader('Content-Type', 'application/json');
}
response.write(bodyToSend); // write a response to the client
response.end(); // end the response
});
}).listen(3099);

npm request send token and header 'content-type': 'application/json' at the same time

I'm trying to get a response back from an API by sending the token and the header 'content-type': 'application/json', but I don't know where should I put them.
This is my code so far:
var request = require('request');
request.get('google example url', {
//
'auth': {
'bearer': '15252727282'
},
"headers": {
"Content-Type": "application/json"
}
}, function (error, response, body) {
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body);
});
This is what I'm getting back in my console:
error: null
statusCode: 401
body: HTTP Token: Access denied.
OK I did it using options as the first parameter and with the following lines:
const options = {
url: 'target url',
method: 'GET',
headers: {
"Authorization": "Token token=12425262",
"Content-type": "application/json"
}
};
request(options, function(err, res, body) {
let json = JSON.parse(body);
console.log(json);
});
You're getting that error because you have never defined require anywhere on your client-side.
Add this to your project: http://requirejs.org/docs/release/2.2.0/minified/require.js
If you want to use require on the client take a look at this http://requirejs.org/.

Categories

Resources