REST API in Wordpress for affiliation system - javascript

I have a web page with links towards other web pages. Once an user clicks in one of those links, a cookie is created, so in case he makes a purchase in the web page, the info related to this link is sent to us through an "API call".
So far, the code I have used in the following:
var storeCookie = getCookie("COOKIE_NAME"); //gets the cookie if it was previously created
if(tiendaCookie!=""){
var request = new XMLHttpRequest();
var url="URL TO A .PHP FILE IN MY SERVER";
peticion.open("POST",url,true);
peticion.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
peticion.send("PARAMETERS OF THE CALL")
The web pages with links on our web page added this code to their web page so the affiliation system can work but we found that when that code is called, the following is returned:
Cross-Origin Read Blocking (CORB) blocked cross-origin response "URL TO A .PHP FILE IN MY SERVER" with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.
I know this is not the right way to set up an API endpoint but I have no knowledge about how to proceed. I was going to try this plugin (https://wordpress.org/plugins/rest-api/) but it looks it is not supported in the latest versions of Wordpress.
What would be the right way to do what I am trying?
Thank you.
EDIT
I have done some more research and I have discovered that the problem might be in my .PHP file, because of:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
But I have this code on the .PHP file:
header("Access-Control-Allow-Origin: *");
What can I be missing?

Related

WordPress publishing failed; javascript shows errors 'Access to fetch ... has been blocked by CORS policy'

I have uploaded WordPress manually on freewebhostingarea.com using my own domain. When I create a new page in Wordpress, I get some errors in javascript console (attached image1) but it lets me add/edit content. When I try to publish the page, I get the error 'Updating failed' and javascript console gives additional errors (attached image2) as below:
"Access to fetch at 'http://e.freewebhostingarea.com/not-found.html' (redirected from 'http://www.shia-match.com/wp-json/wp/v2/pages/16/autosaves?_locale=user') from origin 'http://www.shia-match.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
What could I be doing wrong?
Errors when creating a new WordPress page,
Errors when trying to publish page
Just had this same problem, the cross origin (CORS) policy blocking fetching by the https:// version of a site from the https://www version.
mediaguru’s answer alerted me to check the wp-config file. I found that I had added these lines, and so removed them:
define('WP_HOME', 'https://www.example.com');
define('WP_SITEURL', 'https://www.example.com');
I then rechecked WP’s Settings > General > WordPress Address (URL) and Site Address (URL). Prior to my edit of the wp-config file, they had displayed the www URL, but greyed out and non-editable. Now they had both reverted to the non www version of the URL (and were editable).
On my (Dreamhost) server, the canonical URL is set to www. So I changed the Settings > General URLs to www and… bingo. Solved.
It sounds like you just copied your wordpress files and db from one location to another? If so, you will need to change settings in your wordpress config as well as in your database to make sure the new location is not referring to the old location's database or files.

(CORS) - Cross-Origin Resource Sharing connection issue

I am currently in the process of creating a browser extension for a university project. However as I was writing down the extension I hit a really weird problem. To understand fully my situation I will need to describe it in debt from where my issue comes.
The extension that I am currently working on has to have a feature that checks if the browser can connect to the internet or not. That is why I decided to create a very simple AJAX request function and depending on the result returned by this function to determine if the user has internet connection or not.
That is why I created this very simple AJAX function that you can see bellow this line.
$.ajax({
url: "https://enable-cors.org/index.html",
crossDomain: true,
}).done(function() {
console.log("The link is active");
}).fail(function() {
console.log("Please try again later.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
So far, as long as I understand what it is doing, it is working fine. For example, if you run the function as it is, it will succsesfully connect to the url and process with the ".done(function..." if you change the url to "index273.index" a file which does not exist it will process with the ".fail(function...". I was happy with the result until I decided to test it further more and unpluged my cable out of my computer. Then when I launched the extension it returned the last result from when the browser had connection with the internet. My explanation why the function is doing this is because it is caching the url result and if it cannot connect it gives the last cached value. My next step to try and solve this was to add "cache: false" after the "crossDomain: true" property but after that when I launch the extension it gives the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://enable-cors.org/index?_=1538599523573. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
If someone can help me out sorting this problem I would be extremely grateful. I would want to apologise in advance for my English but this is not my native language.
PS: I am trying to implement this function in the popup menu, not into the "content_scripts" category. I am currently testing this under Firefox v62.0.3 (the latest available version when I write this post).
Best regards,
George
Maybe instead of calling the URL to check if the internet connection is available you could try using Navigator object: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/connection
unless the remote server allowed origin (allowed cors) then you can't access it because it's a security issue.
But there are other things you can do:
You can load image and fire event when an image is loaded
You can access remote JSON via JSONP response
but you can't access other pages because (unless that server allows it) it's a security issue.

Resolve "No 'Access-Control-Allow-Origin' header is present" issue with Chrome Extension

I am developing a Chrome Extension that pre-populates fields then submits the form on an external website when I visit it.
It works perfectly when the data is hard-coded into my script.js file.
However, I'd like to grab the username from an element in my Intranet home page & use this in the script instead of hard coding it.
I have made a simple script.js to test this works:
script.js:
$.get('https://intranet/index.php', function(data){
alert('test');
});
When I try to use this in my Extension and reload the page, I get the error:
XMLHttpRequest cannot load https://intranet/index.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'chrome-extension://eecikfibchjhmochelhmhlimbcjglldf' is therefore not allowed access. The response had HTTP status code 401.
When this same code is run at https://intranet/test.html it works perfectly.
test.html:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<script type="text/javascript">
$.get('https://intranet/index.php', function(data){
$(document.body).load('https://intranet/ #username');
});
</script>
index.php:
<?php
header("Access-Control-Allow-Origin: *");
echo '<div id="username">username</div>';
?>
I have read that some use JSONP to resolve this issue. Does anyone have experience of this?
Can anyone provide help/advice on this issue?
Thank you for any guidance.
There seem to be two issues here at once.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Doesn't look like you thoroughly searched for solutions, since it's a common problem. Anyway, there are 2 ways to solve this:
On the extension side. If you have host permissions, you can do cross-origin requests regardless of CORS headers. (note: "When this same code is run at https://intranet/test.html it works perfectly" highlights that the issue is cross-origin but works on the same site).
There's a whole extension documentation article on this: Cross-Origin XMLHttpRequest, but an ultra-short version: you need to add permissions for the site in the manifest:
"permissions": [
"https://intranet/*"
],
On the server side, by adding a Access-Control-Allow-Origin: * header. Note that this solution opens a certain attack surface (not only your extension can do requests now), so approach 1 is preferable.
That said: you tried to implement approach 2, and it didn't work. Why? Because there is a second problem:
The response had HTTP status code 401
HTTP 401 is "Unauthorized". Your requests lack the authorization necessary - which you don't see when using the intranet site itself, since the browser already have those credentials cached.
But they won't be applied to cross-origin requests, so you get a 401 error page instead of the intended page - that doesn't contain your header.
You need to provide authorization along with the request. jQuery allows that:
$.get(
{
url: 'https://intranet/index.php',
username: '...',
password: '...'
}, function(data){
alert('test');
}
);
I think it should be obvious that this shouldn't be hardcoded in the extension.

How to fetch a Wikipedia webpage with AJAX or fetch()

I want to dynamically fetch a Wikipedia webpage in the browser in order to further process the XHTML with XSLTProcessor.
Unfortunately, this does not work because I can't get Wikipedia to send the "Access-Control-Allow-Origin" header in the HTTP response.
I tried to include the "origin" parameter as it is stated on https://www.mediawiki.org/wiki/Manual:CORS, but without success.
It is important to me to obtain the complete web page HTML as it is obtained by the browser when navigating to that page, so the MediaWiki API is out of the question for me.
This is what I have tried:
var url = "https://en.wikipedia.org/wiki/Star_Trek?origin=https://my-own-page.com";
fetch(url).then(function(response){
console.log(response);
});
Unfortunately, this does not work because I can't get Wikipedia to send the "Access-Control-Allow-Origin" header in the HTTP response.
No, you can't. It is up to Wikipedia to decide if they want to explicitly grant permission to JavaScript running on other sites access to their pages.
Since this would allow users' personal information to leak (e.g. logged in Wikipedia pages display the user's username, which could be used to enhance a phishing attack), this is clearly something undesirable.
var url = "https://en.wikipedia.org/wiki/Star_Trek?origin=https://my-own-page.com";
origin is an HTTP request header, not a query string parameter, and is automatically included in cross origin XMLHttpRequest/fetch requests without you needing to do anything special.

ajax file download from facebook

i am trying to download a file from facebook, for example
https://www.facebook.com/download/847027648649013/36654984.doc
using jquery's ajax (not to disk, to js variable...).
since this is for debug purposes i disabled my chrome's 'same origin policy' using -allow-file-access-from-files -disable-web-security
the problem is - im getting 404 while if i put this link in a new browser tab ill get 302 and then a redirect to the actual file.
how would i download this file?
thanks!
You can get the contents of the file using a jquery get function.
The site you are trying to get the file can not container a No Access-Control-Allow-Orign header,
If it does you will recieve the following javascript error:
XMLHttpRequest cannot load https://www.facebook.com/download/847027648649013/36654984.doc". No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://fiddle.jshell.net' is therefore not allowed access.
If you have permission to access the file from another domain or from a file not hosted in the same domain in other words you can you use the following JQuery code:
var url = "https://www.facebook.com/download/847027648649013/36654984.doc";
$.get(url,
function(data){
//store the file contents in the result variable
var result = data;
});
i ended up using a php proxy.
using php's curl solved both sop problem (no need for -disable-web-security) and does the redirect automatically. now i only need to parse the result....

Categories

Resources