HTTP POST 403 Unauthorized - javascript

The function "myFunction" makes a call on a authentication API, which returns a token. Im taking the token into the variable "token" and setting it as header in my next request (in the "deploy" function), but im only getting 403 unauthorized. I tried to make the same call with the same token in Postman, which worked perfectly. Am i doing something wrong with the token here?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>API TEST</title>
</head>
<body>
<button onclick="myFunction()">Authenticate</button>
<button onclick="deploy()">Deploy</button>
<div id="result"></div>
<script>
var token = "";
function myFunction() {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
alert(this.status);
alert(this.readyState);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
var json = JSON.parse(this.responseText)
token = json["token"];
}
};
xhr.open("POST", "url");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send(JSON.stringify({"username": "mariero\\nabilo", "password": "test"}));
}
function deploy() {
alert(token);
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
alert(this.status);
alert(this.readyState);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhr.open("POST", "url");
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.setRequestHeader("X-Authorization", token);
xhr.send(JSON.stringify({
"taskRelativePath":"My Tasks\\Siebel_RBT-1_Prod_IE.atmx",
"botRunners":
[{
"client":"D00460.lyse.no",
"user":"mariero\\RBT-LYD-1"
}]
}));
}
</script>
</body>
</html>

Related

How to parse json using ajax script in ESP32 app

I am working on a project using ESP32, I get some data from some sensors and send it to a webpage hosted in the same board.
I read some info on the web and understood that is "better" to send all data from several sensors using json method, so my function to get and send data is this:
void handle_leituras()
{
String results_json = "{ \"data\": " + Data +
"," + "\"hora\": " + Hora +
"," + "\"temp_amb1\": " + Tout + " }";
server.send(200, "application/json", results_json);
}
Testing above function in serial monitor I have this data:
{"data": Domingo, 12/4/2020,"hora": 20:53,"temp_amb1": 25.75}
I found a script that can get only one data and print it on that page, this is the script:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("DATA").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "leituras", true);
xhttp.send();
}
Its my index page code that shows data on webpage:
const char pag_inicial[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My 1st test</title></head>
<html>
<body>
<div id="pagina">
<h1>System XPTO</h1>
<div>
Data: <span id="DATA">ND</span><br>
Hora: <span id="HORA">ND</span><br>
Temperatura Ambiente: <span id="TEMPAMB1">ND</span>
</div>
<div id="botoes">
<button type="button" onclick="sendData(0)" style="width: 80px; height: 30px; margin: 30px;">ON</button>
<button type="button" onclick="sendData(1)" style="width: 80px; height: 30px; margin: 30px;">OFF</button><BR>
</div>
<script>
setInterval(function() {
// Call a function repetatively with 1 Second interval
getData();
}, 1000); //2000mSeconds update rate
//function to set on / off a LED on my board
function sendData(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LEDState").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "setLED?LEDstate="+led, true);
xhttp.send();
}
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
</script>
</div>
</body>
</html>
)=====";
My problem is...I don't know how to modify this script to get more sensors values from the described above function.
Anybody can save me please?
Thanks in advance ;)
The standard XMLHttpRequest only supports responseText and responseXML, it does not support responseJSON property. However, as long as your server is sending a valid serialised JSON string, the responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse(), and then you can access each JSON element with dot notation:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
This piece of code works for all browsers that supports XMLHttpRequest and JSON as long as the server is sending a valid JSON object.

I get the Error code 401 when I run this script, what can I do?

I am a newbie in programming.
I have a sensor that is connected to the app via bluethooth. The app sends the data to the cloud service. I got a link from the cloud service that contains the data in a json format. Now I want this data to be displayed on my Website, but its cross domain and whatever I do it says 401 (Unauthorized).
<html>
<head>
<title>Sensor</title>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>Sensor</h1>
<button onclick="myFunctionPost()">Start</button>
<div id="result" style="color:red"></div>
<script>
function myFunctionPost() {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
}; getJSON('https://thetablewheremydatais$format=json').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
}
</script>
</body>
</html>
Have you tried this line of code before you call the server with xhr.send()
xhr.withCredentials = true;

Web Scraping Youtube URL on Genius with Request

I am using request along with cheerio to try to grab the link to a song on genius.com. The URL should be a YouTube link. The problem is that I simply cannot get the 'a' element to return its href attribute. This is my code (cheerio and request are loaded farther up in the script).
request('https://genius.com/Eminem-the-monster-lyrics' , function (error, response, body) {
if (!error && response.statusCode == 200) {
var $ = cheerio.load(body);
var url = $('a' , 'div.song_media_controls-provider-icon').attr('href');
}
console.log(url);
});
I apologize if its a stupid problem or a stupid post. I'm still learning with all of this. Thank you to anyone for help.
// jQuery cross domain ajax
$.get("https://genius.com/Eminem-the-monster-lyrics").done(function (data) {
console.log(data);
});
// using XMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "https://genius.com/Eminem-the-monster-lyrics", true);
xhttp.send();
<!DOCTYPE html>
<html lang="en">
<head>
<title>NK Chaudhary</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="demo">Add here genius.com</div>
</body>
</html>

Uncaught TypeError: request.open is not a function

Code:
// urlget.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX GET-request example</title>
</head>
<body style='text-align:center'>
<h1>Loading Web page into DIV</h1>
<div id='info'>This sentense will be replaced</div>
<script>
nocache = "&nocache=" + Math.random() * 1000000
request = new ajaxRequest()
request.open("GET", "urlget.php?url= amazon.com/gp/aw " + nocache, true)
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML = this.responseText
}
else alert('AJAX error: Data not received')
}
else alert("AJAX error: " + this.statusText)
}
}
request.send(null)
function ajaxRequest()
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActivateXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
function ret(request){return request}
ret(request)
</script>
</body>
</html>
I get this error:
Uncaught TypeError: request.open is not a function
request = new ajaxRequest() is not how you instantiate an AJAX request with JQuery. As such, request doesn't become initialized to an XMLHttpRequest object and therefore it has no open method.
See this for JQuery AJAX.

Call to Api Marine Traffic javascript

I'm making this api call and not getting any results. When I make the call from the browser and search with that imo, I get back the vessel information but not in the call from code.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="pr"></div>
<script>
getInfoVessel("9146314");
function httpGetAsync(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
callback(xmlHttp.responseText);
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
function getInfoVessel(IMO){
httpGetAsync('http://services.marinetraffic.com/api/exportvessel/v:5/7[herecomesthekey]/protocol:jsono/imo:9146314', function(response) {
document.getElementById('pr').innerHTML = response;
});
}
</script>
</body>
</html>
The response is good Status Code:200 OK but there is an error in the response KEY NOT FOUND.
Try this code:
function httpGetAsync(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
callback(xmlHttp.responseText);
}
}
}
function getInfoVessel(IMO){
httpGetAsync('http://services.marinetraffic.com/api/exportvessel/v:5/7[herecomesthekey]/protocol:jsono/imo:' + IMO, function(response) {
console.log(response)
document.getElementById('pr').innerHTML = response;
});
}
getInfoVessel("9146314");

Categories