Avoid CORS while calling SHAREPOINT REST API - javascript

I've created VS project - Sharepoint add in (sharepoint-hosted). Im trying to call sp rest api from js ajax, code below.
$.ajax({
url: "http://MYSITE/_api/web/lists/getbytitle('Kontrahenci')/items",
method: "GET",
headers: {
"Accept": "application/json; odata=verbose",
"Access-Control-Allow-Origin": "*"
},
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (data) {
var results = data.d.results;
for (var i = 0; i < data.d.results.length; i++) {
console.log(data.d.results[i].Title);
}
},
error: function (error) {
console.log(error);
}
})
But i cannot do that, im always getting error:
XMLHttpRequest cannot load
http://MYSITE/_api/web/lists/getbytitle('Kontrahenci')/items.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin
'http://app-802ce2286e9d83.MYSITE' is therefore
not allowed access. The response had HTTP status code 401.
Ofc MYSITE = my url address.
I can connect via browser to url from ajax, and after authorizing (login,password from sharepoint) im getting data.
I also added in app.manifest permissions for Lists(read, and selecting list while building app) and full-control for Web.
When im enable chrome sth like that it works:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
--disable-web-security --user-data-dir="D:\chrome"
But its not a solve of this problem.

Related

Fix CORS error without disabling security in chrome

I have a javascript code which loads json data from some json_url using ajax requests I am getting folloowing error when running the html in chrome
Access to XMLHttpRequest at json_url from origin 'http://localhost:8000' 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.
To fix this error I am opening chrome by disabling web security through the following command
google-chrome --disable-web-security --user-data-dir="/tmp/chrome_dev_test"
Is there anyway to fix this error so that I can run html on chrome without disabling web security every time?
front-end code used:
function getJSON(url){
$.ajax({
type:'GET',
url:url,
dataType:'json',
contentType:'application/json',
timeout: 3000,
success:function(data){
//do something with data
}
});
}
You need to enable CORS on your server side. Here's a guide for many servers, use what suits you.
https://enable-cors.org/server.html
Also in your client-side code, when you specify your request add that it's a CORS request. For example:
$.ajax({
url: "http://www.someotherdomain.com",
type: "POST",
crossDomain: true, //<-- this right here
data: JSON.stringify(somejson),
dataType: "json",
success: function (response) {
// ...
},
error: function (xhr, status) {
// ...
}
});

API get cross domain issues - Cross-Origin Read Blocking (CORB)

I'm trying to use API to get information about a specific user based on user ID. I need to use basic auth and pass some headers with my call.
I'm getting this:
Cross-Origin Read Blocking (CORB) blocked cross-origin response "rest/user/getProfile?callback=jQuery224033348109431646855_1548684613983&userId=24068..." with MIME type text/plain.
My code:
$.ajax
({
type: 'GET',
crossDomain: true,
async: false,
url: 'example_URL_/api/user/getProfile',
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
},
beforeSend: function (xhr) { xhr.setRequestHeader("Authorization", "Basic ZHVubmVzYXBpskjoi43u5409543o9tI654kjhugjy"); },
dataType: 'jsonp',
data: { "Id": "1234" },
success: function (data) {
console.log(data);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
}
});
is there anything I'm missing?
You said:
dataType: 'jsonp',
… so jQuery makes a JSONP request (i.e. inserts a <script> element).
The browser makes a request to the URL and the server said:
Content-Type: text/plain
Since a plain text document is not a JavaScript program, the browser refused to execute it and threw a CORB error instead.
A JSONP response must be application/javascript, not text/plain.
You need to either:
Not make a request for JSONP
Change the server to respond with JSONP
Aside: Since you are using JSONP, the type, crossDomain, async, headers, and xhr.setRequestHeader properties have no effect.
Since you said you needed to set basic auth, that rules out option two. You can't use JSONP for this.
In your API configure CORS to accept all domains, or enter the domain that you're using to send the request from.
If your API is created by PHP here is an example:
<?php
header("Access-Control-Allow-Origin: *");
Or if you are using a third party API, try to see the documentation. I'm sure there will be a part talking about CORS.

$.ajax requests with CORS

I'm having troubles with an AJAX request. I was getting the below error:
Error: Access is denied
I tried this jQuery AJAX request:
$.support.cors = true;
$.ajax({
url: 'http://testwebsite.com/test',
type: "GET",
dataType: 'json',
contentType: 'application/json',
crossDomain: true,
headers: {
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Origin': 'http://testwebsite/test',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true'
},
xhrFields: {
withCredentials: true
},
success: function(data) {
alert("Data from Server" + JSON.stringify(data));
},
error: function(jqXHR, textStatus, errorThrown) {
alert("You can not send Cross Domain AJAX requests: " + errorThrown);
}
});
Can anyone kindly let me know what I am missing. Thanks in advance.
As rory-mccrossan mentioned in a comment, CORS protection is designed so that a website cannot directly access the content of another website (in a browser) unless the website being accessed agrees to it.
It would completely ruin the point of CORS if a site just has to send some headers in order to circumvent the defence
Instead, you will need to use a CORS proxy. It's a server that when given a request like yourCORSproxy.example.com/http://testwebsite/test would load the page and return it, but with CORS allowed (like a normal proxy but with CORS enabled).
One of these CORS proxies is https://crossorigin.me, but at the time of writing this it is down. It might be more stable if you simply create your own proxy.
tl;dr: testsite.test should be sending the headers on its response. You should not be sending the headers on your request.

Cross domain request to web-service returning JSON with jQuery

I'm trying to doing a request to a web service from an ASPX page on www.mysite.com using jQuery.
My webservice is hosted on https://www.mysite2.com.
I've tried to perform the request in this way (I found part of this code online):
$.ajax({
url: "https://www.mysite2.com/ws/api/Visits/List/" + myfilter,
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
beforeSend: setHeader,
crossDomain: true,
success: function (data) {
response($.map(data.visits, function (v, i) {
return {
label: v.ID,
value: v.Name
}
}))
},
error: function () {
alert('Error!');
},
})
function setHeader(xhr) {
xhr.setRequestHeader('X-Token', 'myToken0123');
}
I encounter two problems:
1) IE is returning Access Denied error (code 0x80070005)
2) Chrome is returning "Insecure response" error
The returned JSON will be used to fill an autocomplete source.
Any suggestion to solve this problem?
If this is a Cross Domain Request then you need to contact whom ever is in charge of the server and ask them to add your domain to their list. This is the code they would need to add to the server where http://foo.example is your domain.
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER
Access-Control-Max-Age: 1728000
If you go to https://www.mysite2.com, it will tell you This server could not prove that it is www.mysite2.com; its security certificate is from *.hawkhost.com. This may be caused by a misconfiguration or an attacker.
You can accept this and you will no longer see your issue. However, every single one of your users would have to do the same.

SOAP-request No 'Access-Control-Allow-Origin' header soapUI header

Im trying to accomplish SOAP-post to get back XML data.
Problem is that "No 'Access-Control-Allow-Origin' header" and I suppose that the server needs to add the header.
So I created a MockService in SOAPui and copied the server response. But I still get the same problem. In soapUI in the response I added this http://imgur.com/TZXM2Ca
function soap() {
var sr = MySoapRequest;
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.setRequestHeader("SOAPAction", "x");
},
type: "POST",
dataType: "xml",
data: sr,
crossDomain: true,
success: function (data) {
console.log(data);
},
error: function (error) {
},
contentType: "text/xml; charset=\"utf-8\""
});
}
By default, browsers cannot make POST requests via AJAX to URLs which are not in the same origin as the current page. For example, if you have open a page that sits in the URL http://foo.com, and that page tries to post some data (via AJAX) to http://bar.com, you will normally get the error you are seeing now.
If you want to make this work, you have to configure your server to accept requests via Cross-Origin Resource Sharing (CORS). I suggest that you get some information about CORS, you can find a lot of documentation online about it. An extensive overview can be found here.
As for the actual implementation of CORS on your server, it depends on which platform you are using. If you are using PHP, have a look at this question.

Categories