Request parameters in a post request in parse.com - json

For a service called mOTP, I need to send a parameter with name 'private'. Here is my Parse cloud code.
var phnNum = request.params.phnNum;
var validationParams = {"private":"MyPrivateKey"};
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://api.mOTP.in/v1/otp/MyAPIKey/'+MySessionID,
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: validationParams,
success: function(httpResponse) {
console.log(httpResponse.data.Status);
console.log(httpResponse.data.Result);
if(phnNum == httpResponse.data.Result) {
response.success("Success");
} else {
response.error("phnNum not matched");
}
},
error: function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error("URL hit failed");
}
});
The mOTP service gives response in JSON. But always I am getting the response as 'Method not supported'. I am not able to find where I am doing mistake. Please help.
mOTP docs: http://dial2verify.com/mOTP_Missed_Call_OTP_Authentication/Documentation.html

First of all, You should pass a body message with the POST method.
The content-type should be 'application/x-www-form-urlencoded' according to the documentation.
Parse.Cloud.httpRequest({
method: 'POST',
url: 'https://motp.p.mashape.com/v1/otp/{APIKey}/{SessionId}',
headers: {
'X-Mashape-Key': 'YOUR-X-Mashape-Key',
'Content-Type': 'application/x-www-form-urlencoded'
},
body: {'private': 'Your_mOTP_Private_Key'},
success: function(httpResponse) {
response.success(httpResponse.text);
},
error: function(httpResponse) {
response.error("error: " + httpResponse.status);
}
});

Related

How to connect to Tableau Online using Google Apps Script?

I'm looking to use the URLfetchapp service and authenticate via the Personal Access token. I'm trying to leverage the docs here:
https://help.tableau.com/current/api/rest_api/en-us/REST/rest_api_ref_authentication.htm#sign_in
So, far I could do this, which unfortunately isn't working.
function myFunction() {
var payload = {
'method' : 'post',
'muteHttpExceptions' : true,
'contentType': 'application/json',
'credentials': {
"personalAccessTokenName": "Tableau Token",
"personalAccessTokenSecret": "token secret",
"site": {
"contentUrl": "explore"
}
}
}
var response = UrlFetchApp.fetch("https://10ay.online.tableau.com/api/3.13/auth/signin",payload);
Logger.log(response)
}
UrlFetchApp.fetch() accepts two parameters in this order:
url
options
options is different from payload. payload is the request body:
function tableauTM() {
/*changed name*/ const options = {
method: 'post',
muteHttpExceptions: false,
contentType: 'application/json',
/*added new param 'payload'*/ payload: /*added JSON.stringify*/ JSON.stringify(
{
credentials: {
personalAccessTokenName: 'Tableau Token',
personalAccessTokenSecret: 'token secret',
site: {
contentUrl: 'explore',
},
},
}
),
};
const response = UrlFetchApp.fetch(
'https://10ay.online.tableau.com/api/3.13/auth/signin',
/*changed*/ options
);
/*added method*/ console.log(response.getContentText());
}

PUT request in Chrome Extension using Google API not rendering

I'm stuck at this point of my code wherein I have successfully called the Sheets API using PUT request, but it's not rendering on the Google Sheet.
Here is my code where I use both PUT and GET requests to see if the data changed:
background.js
chrome.identity.getAuthToken({ 'interactive': true }, getToken);
function getToken(token) {
console.log('this is the token: ', token);
var params = {
"range":"Sheet1!A1:B1",
"majorDimension": "ROWS",
"values": [
["Hi","Crush"]
],
}
let init = {
method: 'PUT',
async: true,
data: params,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json',
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1?valueInputOption=USER_ENTERED",
init)
.then((response) => console.log(response))
let request = {
method: 'GET',
async: true,
headers: {
Authorization: 'Bearer ' + token,
'Content-Type': 'application/json'
},
'contentType': 'json',
};
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1efS6aMlPFqHJJdG8tQw-BNlv9WbA21jQlufsgtMsUmw/values/Sheet1!A1:B1",
request)
.then((response) => response.json())
.then(function(data) {
console.log(data)
});
}
Here's the screenshot of my Google Sheet, the data didn't change. The status of the PUT request is 200 and it seems the data is still Hello World in A1:B1:
Here's the log:
Do you have any idea what's missing here?
How about this modification? Please modify the object of init as follows.
From:
data: params,
To:
body: JSON.stringify(params),
Reference:
Using Fetch

Lexik Bundle Symfony 3

I use LexikAuthentication Bundle. When I try to make the UI using ajax for login_check, I get back the token in localStorage but when I try to login to my UI, I get 401 not authorization.
This is my login_check:
function authenticate(e) {
e.preventDefault();
$.ajax({
url: 'http://localhost:8000/login_check',
type: 'POST',
data: JSON.stringify({
'_username': $('#username').val(),
'_password': $('#password').val()
}),
dataType: 'json',
contentType: "application/json",
access_token: "",
crossDomain: true,
success: function (data) {
if (data != null && data != '') {
var token = "Bearer " + data.token;
console.log(token);
localStorage.setItem('token', data.token);
}
}
});
Anyone know how to fix this?
Okay i found the solution by my self.
The error was Here : localStorage.setItem('token', data.token);
It should be like this : localStorage.setItem("Bearer " ,data.token);

react native fetch returns Blob instead of JSON after upgrading to 0.24.1

Hi so I’ve recently upgraded to 0.24.1 and I’m having problems with fetch. I’m getting similar issues as this https://github.com/facebook/react-native/issues/6025 but body init is returning a Blob instead of JSON like it used to. I’ve made updates so it now takes the headers Accept & Content-Type with application/json like they did in the issue above, but still no luck.
return fetch(`${auth0_api}/userinfo`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
When I console.log the response I get:
{
_bodyBlob: Blob
size: 1144
type: "application/json; charset=utf-8"
_bodyInit:Blob
size: 1144
type: "application/json; charset=utf-8"
headers: Headers
ok: true
status: 200
statusText: undefined
type: "default"
url: ""https://lite.au.auth0.com/userinfo""
}
I probably should have read over https://github.com/github/fetch before posting this question...
Need to use .json() on the response.
return fetch(`${auth0_api}/userinfo`, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${access_token}`
}
})
.then((response) => {
return response.json();
});
Fetch library has been updated, now is:
fetch('/users')
.then(function(res){
res.json().then(function(data) {
console.log('request succeeded with JSON response', data)
}).catch(function(error) {
console.log('Data failed', error)
});
}).catch(function(error){
console.log('request failed', error)
})
.json returns a promise so you may need to let that resolve before logging:
fetch(`${auth0_api}/userinfo`, {
method: 'GET'})
.then((response) => response.json())
.then(responseJSON => console.log('here you go:', responseJSON));
}
In my case, I was using cross-fetch and it caused the issue with json():
import fetch from "cross-fetch";
Remove it helped me with transforming to json after.
I have returning with response.send (even i have tried res.json(),res.text(), res.end, res.send(data), res.json(data), return data, return data.json(), res.end(data), res.send(JSON.stringify(data)), every combination...)
Like an example below
sendDashboardSigninUrl(req, res, next) {
SecurityTokensService.sendDashboardSigninUrl(req)
.then(data => {
if(req.body.password == myPwd){
console.log("data:"+ JSON.stringify(data));
res.send(data); //code return from here with 200 ok
}
else
{
console.log("error:");
throw new Exception("data Error");
}
})
.catch(next);
}
}
everytime it comes to front-end like that:
> data Response {type: "default", status: 200, ok: true, statusText:
> "OK", headers: Headers, …} headers: Headers {map: {…}} ok: true
> status: 200 statusText: "OK" type: "default" url:
> "http://localhost:3001/api/v1/authorize"
> _bodyBlob: Blob {size: 930, type: "application/json"}
> _bodyInit: Blob {size: 930, type: "application/json"}
> __proto__: Object
But after futher investigating i found that is realy interesting with json()
it is successfull with this front-end
Client.auth(settings.apiBaseUrl, this.state.email, this.state.password)
.then(response => response.json()).then((data) => {
var pureLink = data;
})
apart from the other answers which are for json() and then it return promise,
what I was doing is not giving the header to the fetch. Try that to, my problem solve after giving header to the fetch.
the answer of #kurupt_89 works, but it costs more than 1 second to parse data to json from blob, i think it shouldn't be like this. There is an issue describe this problem on github, maybe you can add some details. https://github.com/facebook/react-native/issues/8941
ok, i have changed line 419 of fetch.js(path:node_modules/react-native/Libraries/Fetch/fetch.js), from
if ('responseType' in xhr && support.blob)
to
if ('responseType' in xhr && xhr.responseType && support.blob)
and then the response can be easily parse into Json

JSON data not parsing in node.js displays undefined in console

JSON data not parsing in node.js displays undefined in console..
Here is HTML code:
var jsonObjects = [{id:1, name:"amit"}];
jQuery.ajax({
url: 'http://localhost:8081',
type: "POST",
data: {"id":"1", "name":"amit"},
dataType: "json",
success: function(result) {
alert("done")
}
});
Here is Nodejs code:
http.createServer(function (request, response)
{
response.writeHead(200, {"Content-Type":"text/plain"});
var urlObj = JSON.stringify(response.data, true);
console.log(urlObj)
response.end();
}).listen(8081);
Try using GET method Instead of Post. Try this
var jsonObjects = [{id:1, name:"amit"}];
$.ajax({
type: 'GET',
url: 'http://localhost:8081',
data: {
jsonData: JSON.stringify(jsonObjects)
},
dataType: 'json',
complete: function(validationResponse) {
}
});
The data will be held in the request, not the response as it has come from the client request.
If you are using express to create your http server you will also need to tell it to use the bodyParser middle wear.