Ive searched for this topic and ended here https://stackoverflow.com/search?q=api+replace+%27GET%27+url+with+a+variable yet no answer seems to addres my question.
this is my code:
function wpp(){
let ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://averylong.url/with/some/stuff/andshit'); <-- wan to to replace this with a variable
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
let data = JSON.parse(ourRequest.responseText);
myHtml(data);
} else {
console.log("server returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
what I want to do is the following
let myNewUrl = localStorage.getItem(449);
function wpp(){
let ourRequest = new XMLHttpRequest();
ourRequest.open('GET', myNewUrl);
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
let data = JSON.parse(ourRequest.responseText);
myHtml(data);
} else {
console.log("server returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
}
But every time I get this error:
GET https://averylong.url/with/some/stuff/449 403 (Forbidden)
but if I copy/paste the very same url in my browswer I get back the json data no problem
EDIT screenshot
console error
I want to thank #ravi his comment lead me way down in to the rabbit hole..... Some things can not being unseen, but I found the answer somewhere.
The problem was ModSecurity it happends that ModSecurity does not like wordpress and you have to disable it or it will return a 403 error, now the funny part is that even when it return a 403 error it will display the results on the 'browser' and 'Postman' and that is why I tought I was writing wrong javascript, it happends that when javascript finds the 403 error just stops and wont render the answer even if it's there. Solution: turn off ModSecurity if you are working with wordpress API.
Related
I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.
Can someone, please, explain to me, why in the code snippet below I get request.response == null?
In my JSON file I have an array with some data, which I want to use further.
After spending a lot of time on finding a problem, I found that there is a problem with link. When I uploaded JSON file into web service and used a link from that, it works fine. But when I use a link to the file in my file system, it doesn't want to work.
let requestURL = "../sliderContent.json";
const request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = () => {
if (request.readyState === 4 && request.status === 200) {
let slidesContent = request.response;
console.log(slidesContent);
returnSlidesReducer(slidesContent);
}
};
I am trying to do a GET request to my server. I have done it many times previously, and everything was working.
But now, when I launch it on Google Chrome, it gives me this error :
GET http://myserver.net:443/searchShoplist/apple net::ERR_CONNECTION_REFUSED
When I launch it on Firefox, I have no result and no response.
Here is the code of my request to the server :
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "http://myserver.net:443/searchShoplist/apple");
xhr.send(data);
Trying to get head around when debugging a Viewer app. Chrome console shows 'The provider id_provider is not a valid one'. Any suggestion?
If options is like this:
var options = {
env: 'AutodeskProduction',
getAccessToken: getToken }
}
function getToken () {
var response;
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
response = JSON.parse(
xhr.responseText);
return response.access_token;
}
if forcing 2.9, 'The provider id_provider is not a valid one'.
If forcing 2.7 or 2.8, not log but the viewer doesn't show up.
If no specified version, 'Warning : no access token is provided. Use built in token : YtTb8vRA4XQfTorjm9c8eVZJTYP6'.
it stops in Autodesk360App.js
var initialItem = app.getDefaultGeometry(geometryItems);
Chrome logs 'Uncaught TypeError: app.getDefaultGeometry is not a function'
If I directly feed token:
accessToken: 'MorPwhKARIS3VGIrcd3FrZSjsnOx5'
it works beautifully in 2.7,2.8 and 2.9. But if no version, it stops in Autodesk360App.js, the same as above.
Thank you!
Aren't you missing the url on the http request? Maybe something line:
function getToken() {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", '/yourTokenEndPoint', false);
xmlHttp.send(null);
var response = JSON.parse(xmlHttp.responseText);
return response.access_token;
}
For the Viewer, it must be synchronous.
I wanna know if it's possible do multiple res.send/json in same method. I have a big problem with that because I wanna develop a function into a Web-Worker to call a put request each minute but in 2nd request I get "can't set headers after they are sent.". I know that it's not possible do it but I wanna know if exist some way to run.
exports.update = function (req, res) {
var feed = req.feed;
feed.title = req.body.title;
feed.apifeed = req.body.apifeed;
feed.apikey = req.body.apikey;
feed.active = req.body.active;
if(feed.apifeed && feed.apikey && feed.active){
var t = Threads.create();
t.eval(setInterval(
function(){
async.parallel([
function(callback, data){
var url = 'https://api.xively.com/v2/feeds/' + feed.apifeed + '.json?key=' + feed.apikey;
sensordata.getSensorData(url, function(data){
callback(null, data);
});
}
], function(err, data){
feed.content[0].value = data[0][0].value;
feed.content[0].date = new Date();
feed.save(function (err) {
if (err) {
return res.status(400).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(feed);
}
});
});
}, 5000)
);
}
};
Thanks for supporting and I wait your responses. Greetings!
You cannot respond to a request more than once, that wouldn't make sense.
If you need to stream data, then you will need to use long polling, WebSockets, Server-sent Events, etc.
Also, assuming Threads.create() does what I think it may be doing, spawning an OS thread just to do what you're currently doing is a waste of resources. Nothing in that block of code is CPU-bound.