Openvidu server API REST with fetch - ajax

I start up KMS+OPENVIDU server with docker. Everything works nice with web component when i use JQ ajax:
For example (this works fine):
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: {
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: response => resolve(response.data.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + OPENVIDU_SERVER_URL + '\"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
}
})
If i put fetch (native javascript) :
var myPromise = fetch(this.ovServerUrl + '/api/sessions', {
method: 'POST',
// mode: 'cors',
// credentials: 'same-origin',
// redirect: 'follow',
body: JSON.stringify(
{ customSessionId: sessionId }
),
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + this.ovSecret)
}
})
return myPromise.then(response => {
console.log('return resolve !response', response)
console.log('return resolve !response.data.id! ', response.data.id)
return response.id
})
I got response but without response.id .
Looks like :
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: false
status: 200
statusText: ""
type: "cors"
url: "https://MY_DOMAIN:4443/api/sessions"
Any suggestion ?

Related

Internal server error 500 for all requests to Google Ads API

Here is my code in Node JS.
var bearerToken = 'Bearer '+ access_token;
var options = {
url: 'https://googleads.googleapis.com/v1/customers/'+accountid+'/googleAds:search',
headers: {
'Authorization': bearerToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
'login-customer-id': '123-456-7890',
'developer-token': 'XXX_XXXXXXXXXXX'
},
form: { 'query': 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id' }
};
request.post(options, function(err, response) {
console.log(response);
});
I keep getting the below error
body: '{\n "error": {\n "code": 500,\n "message": "Internal error encountered.",\n "status": "INTERNAL"\n }\n}\n' }
500 error code means the error is from Google. Is this the case or am I doing something wrong here?
After breaking my head with multiple iterations. Finally, I figured out that the problem was with the developer-token. I had to generate a new developer-token and change form to json. It's working fine now.
Here is the final working code
var bearerToken = 'Bearer '+ access_token;
var options = {
url: 'https://googleads.googleapis.com/v1/customers/'+accountid+'/googleAds:search',
headers: {
'Authorization': bearerToken,
'Accept': 'application/json',
'Content-Type': 'application/json',
'developer-token': 'XXX_XXXXXXXXXXX'
},
json: { 'query': 'SELECT campaign.id, campaign.name FROM campaign ORDER BY campaign.id' }
};
request.post(options, function(err, response) {
console.log(response);
});

Getting 500 error on some docs but not others. Why?

My add-in for MS Word works for some docs but not others. For test-doc-A, it works fine. I get the results I want. test-doc-B throws a 500 error on the $.ajax call that sends the text to the server. Both docs are one page. Granted, 500 errors are supposed to be "server" side. But what could be so different between these docs that's causing this?
The server logs don't indicate anything (to my eye) that tells me what the issue is.
test-doc-A (All Good)
2019-02-28 23:41:33 MyApiEndPoint POST /api/Document/Upload X-ARR-LOG-ID=8b253a46-bca8-4981-9ded-3fdf671fe63c 443 - myIpAddressMozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+Touch;+rv:11.0)+like+Gecko - https://localhost:44399/Home.html?_host_Info=Word$Win32$16.01$en-US myServerUrl 200 0 0 664 3793 46
test-doc-B (500 Error)
2019-02-28 23:42:13 MyApiEndPoint POST /api/Document/Upload X-ARR-LOG-ID=b0095aa0-9fc5-4a26-83b0-40d44ff160ba 443 - myIpAddress Mozilla/5.0+(Windows+NT+10.0;+WOW64;+Trident/7.0;+Touch;+rv:11.0)+like+Gecko - https://localhost:44399/Home.html?_host_Info=Word$Win32$16.01$en-US myServerUrl 500 0 0 326 11306 46
Is there some way to compare the text that's being sent? Am I using the right method 'range.load("text")'?
The only difference between the docs appears to be formatting. But, I'm just sending the text, regardless of formatting, aren't I?
Do I need to "clean" the text before sending? Just so confused, right now.
function sendTextToServer() {
Word.run(function (context) {
var doc = context.document;
var range = doc.body;
range.load("text");
return context.sync()
.then(function () {
var myData = '{\"FileName\": \"WordAddIn-Test\",\"Text\": \"' + range.text + '\" }';
// begin promise
var promise = $.ajax({
url: urlToUse + "/Upload",
method: 'POST',
contentType: 'application/json; charset=utf-8',
beforeSend: function (request) {
request.setRequestHeader("Authorization", "Negotiate");
},
crossDomain: true,
dataType: 'json',
processData: false,
cache: false,
data: myData,
success: function (data) {
log("sendTextToServer Success: " + JSON.stringify(data));
},
error: function (xhr, textStatus, errorMessage) {
log("sendTextToServer promise Error: " + errorMessage + " : " + JSON.stringify(xhr) + " : " + textStatus);
}
});
// end promise
// do something with promise
promise.done(function (data) {
myDocID = data.documentID;
log("sendTextToServer myDocID: " + myDocID);
log("url = " + urlToUse + "/Status?documentID=" + myDocID);
setTimeout(function () { goDoSomethingElse(); }, 2000);
});
})
.then(context.sync);
}).catch(function (error) {
log("Error: " + error);
if (error instanceof OfficeExtension.Error) {
log("Debug info: " + JSON.stringify(error.debugInfo));
log("Something went wrong. Trying again");
}
});
}
"Looks like I picked the wrong week to quit sniffing glue."
~Steve McCroskey

unsupported_grant_type in Web Api 2

i am beginner in Web Api and implementing authorization and authentication but getting some error as i mentioned below:
I am getting this error while getting token from webApi
{"readyState":4,"responseText":"{\"error\":\"unsupported_grant_type\"}","responseJSON":{"error":"unsupported_grant_type"},"status":400,"statusText":"Bad Request"}
This is my jQuery code to make request for token
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});
Your data should be like query string, not JSON object. And you should encode params if need
data: 'username=' + encodeURIComponent(user.username) + '&password=' + encodeURIComponent(user.password) + '&grant_type=password'
contentType is wrong. It should be application/json
$(document).ready(function () {
$("#login").click(function () {
debugger;
var details = "{'grant_type':'password', 'username': '" + $("#UserName").val() + "', 'password': '" + $("#Password").val() + "' }";
console.log(details);
$.ajax({
type: "POST",
contentType: "application/json",
data: details,
url: "http://localhost:59926/token",
success: function (data) { console.log(JSON.stringify(data)); },
error: function (data) { console.log(JSON.stringify(data)); }
});
});

Force.com : Rest API Bad Request in Query Like

I got 'bad request" message on the below Rest API Ajax call, When I tested on Developer console it return data successfully.
var _url = auth.get("instance_url") +
"/services/data/v28.0/query/?q=SELECT Id, Name FROM Account WHERE Website LIKE '%gmail.com%' ";
$.ajax({
url: _url,
cache: false,
async: false,
type: 'GET',
contentType: 'application/json',
headers: {
'Authorization': 'OAuth ' + auth.getAccessToken()
},
success: function (data) {
console.log("accounts: " + JSON.stringify(data));
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + +errorThrown);
}
});
You need to URLEncode the query parameter, spaces are not valid in a query string, e.g.
var _url = auth.get("instance_url") + "/services/data/v28.0/query?q=" + encodeURIComponent("select id,name from account");

Why can Twitter API Authorization data be sent through GET or POST params instead of HTTP headers?

I'm using oauth.js and sha1.js in a Greasemonkey script:
// ==UserScript==
// #name twitter_api
// #namespace twitter
// #include *
// #version 1
// #require http://oauth.googlecode.com/svn/code/javascript/oauth.js
// #require http://pajhome.org.uk/crypt/md5/sha1.js
// ==/UserScript==
var url = "https://api.twitter.com/1.1/statuses/update.json";
var accessor = {
token: "XXX",
tokenSecret: "XXX",
consumerKey : "XXX",
consumerSecret: "XXX"
};
var message = {
action: url,
method: "POST",
parameters: {status: "apitest"}
};
OAuth.completeRequest(message, accessor);
OAuth.SignatureMethod.sign(message, accessor);
var authorization = "OAuth oauth_consumer_key=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_consumer_key) + "\""
+ ", oauth_nonce=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_nonce) + "\""
+ ", oauth_signature=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_signature) + "\""
+ ", oauth_signature_method=\"HMAC-SHA1\""
+ ", oauth_timestamp=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_timestamp) + "\""
+ ", oauth_token=\"" + encodeURIComponent(OAuth.getParameterMap(message.parameters).oauth_token) + "\""
+ ", oauth_version=\"1.0\"";
Using Authorization header with POST request:
GM_xmlhttpRequest({
method: "POST",
url: url,
data: "status=apitest",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": authorization
},
onload: function(response) {
alert(response.responseText);
}
});
Using GET params only with POST request:
GM_xmlhttpRequest({
method: "POST",
url: url + '?' + OAuth.formEncode(message.parameters),
onload: function(response) {
alert(response.responseText);
}
});
Using POST params only with POST request:
GM_xmlhttpRequest({
method: "POST",
url: url,
data: OAuth.formEncode(message.parameters),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
onload: function(response) {
alert(response.responseText);
}
});
Why do this 3 AJAX requests work when Twitter clearly says you have to send an Authorization header?
https://dev.twitter.com/docs/auth/authorizing-request
If both GET, POST, HTTP header Authorization are accepted, why should I prefer HTTP header, is it more secure or maybe it doesn't matter since it's an API call?

Resources