access token passed as query param becomes invalid on using request module - javascript

I am using the contentful (CMS platform) api to get the user details by userId by using request module. Here, the access-token is passed as query param which the system recognizes as invalid. But I am not sure if there is any wrong in the way I am passin the query param.I am pretty sure the token passed is valid as I can get the proper result using rest-client. Code is given below:
request.get(
{
url:
"https://api.contentful.com/organizations/organizationId/users/userId",
qs: {
access_token:
" CFPAT-xxxxxxxxxxxxxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx "
},
headers: {
Authorization:
"CFPAT-xxxxxxxxxxxxxsxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"x-contentful-enable-alpha-feature": "organization-user-management-api",
"Content-Type": "application/json"
},
method: "GET",
json: true
},
function(error, response, body) {
console.log(body);
}
);
Error:
{ requestId: 'e102c744950f39fdabad9ae942ac16ba',
message:
'The access token you sent could not be found or is invalid.',
sys: { type: 'Error', id: 'AccessTokenInvalid' } }

Related

Fetch error - Receiving 405 GET Method Not Allowed While Using POST

I am trying to deploy an app where I have to register to get a JSON with my data (username, email, password) from the backend. I linked the frontend to backend with a fetch (the code is attached). My fetch request has a POST method, but I get this error, whilst I am not using any GET method, why so?
fetch('link/signup' /*will be changed with correct URL tomorrow*/,{
method: 'POST',
/* method: 'POST',
body: formData, */
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
username: username.value,
email: email.value,
password: password.value,
}),
}).then((response) => {
return response.json();
})
.catch((error) => {
console.log('Request failed', error);
});
GET https://link/signup/ 405 (Method Not Allowed) (anonymous) #
registration.9bbdb929a0502d2a723f.js:68
It's weird, but some APIs are not case-sensitive. Try to write 'post' instead 'POST' and see

Node.JS Invalid URI Error: GET Request using Query parameter

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

Node/Express - res.status().send() only sends the status but does not send an object

I am having an issue with a route in my backend where res.status().send() will only send the client the status code, but it will not send the client the object located inside of send().
Here is my code (redacted all code but the problem for brevity):
exports.user_signup = (req, res) => {
const { body } = req;
const { companyName, password, email } = body;
User.find({ email: email }, (err, previousUsers) => {
if (err) {
return res.status(400).send({
message: "There was an issue signing up."
});
} else if (previousUsers.length > 0) {
return res.status(403).send({
message: "Records show this email is linked to another account."
});
}
}
When I make my fetch request from the client, the response only returns the status code from the server, but nowhere in the response is the object in the send() method on the server. Just spitballing, I threw res.status(200).json(object) at it to send the object as json to no avail.
Here is my `fetch request from the client:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
}).then(response => console.log(response));
}
To show what response I am getting, I purposely posted some form data from the client to the route that would throw the 403 error, and this is the response I get in the browser console:
Response {type: "basic", url: "http://localhost:3000/users/accounts/", redirected: false, status: 403, ok: false, …}
So I am able to successfully send the status back from the route to the client, however I can not for the life of me figure out why send() does not send the object along with it.
The body of the response that comes back from fetch() is a ReadableStream. You need to process it to turn it into something usable. Normally you would call response.json() to parse it as a JSON object:
fetch("http://localhost:3000/users/accounts/", {
method: "post",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(userData)
})
.then(response => response.json())
.then(response => console.log(response));
}

Spotify Api Ajax Post request to get token using the 'ajax-request' node package

I'm trying to receive a token from the Spotify api to allow me to search the api and such for songs and other information.
On my sever application index.js I start by requiring the package:
var request = require('ajax-request');
Later on I go to request my token:
request.post({
method: 'POST',
url: 'https://accounts.spotify.com/api/token',
'Content-Type' : 'application/x-www-form-urlencoded',
header: {
Authorization: 'Basic' + <urlEncodedClientIdAndClientSecret>,
},
data: {
grant_type: 'client_credentials'
}
}, function(err, res, body) {
});
However if I try and console log this it always returns undefined, is there an issue with how I've laid out my post request or is there something else I'm missing?
Oh....I just looked at your request again....are you missing a space after the "Basic"? Try this:
Authorization: 'Basic ' + <urlEncodedClientIdAndClientSecret>,

How to make a POST request using CustomVision api with NodeJS

I'm trying attach an image using the bot emulator tool and sending this image off to the microsofts customvision api, the issue I'm having is that I get
{ Code: 'BadRequestImageFormat', Message: '' }
back from custom the custom vision api call.
I'm using the the request module from npm to handle the calls
// Receive messages from the user and respond by echoing each message back (prefixed with 'You said:')
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'xxx',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/octet-stream',
'Prediction-Key': 'xxx'
},
body: session.message.attachments[0]
}, function(error, response, body){
console.log(body);
});
}
});
I believe that I may be sending the wrong format through to custom vision however I have been unable to figure it out as of yet.
I replicated your issue and it looks like the problem is your 'Content-Type'. You're attempting to pass JSON in your request, but setting the content-type as octet-stream. See my modified code below:
var bot = new builder.UniversalBot(connector, function (session) {
session.send("Hello"); //session.message.text
// If there is an attachment
if (session.message.attachments.length > 0){
console.log(session.message.attachments[0])
request.post({
url: 'https://northeurope.api.cognitive.microsoft.com/vision/v1.0/analyze?visualFeatures',
encoding: null,
json: true,
headers: {
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': 'Your API Key...'
},
body: session.message.attachments[0]
},
function (err, response, body) {
if (err) return console.log(err)
console.log(body);
});
}
});
When I run this, I get the error InvalidImageUrl which is to be expected as it's looking for a content on localhost. You could get round this by exposing your localhost using Ngrok.

Categories

Resources