Get text from private stash link - javascript

I have application where I getting code from stash raw file. Scrapping from public repositories is simple, it looks like this:
public getRawFile(rawLink: string) {
return this.http.get(rawLink).map((res: Response) => res.text());
}
But now I would like to get code from stash raw file, but from private repository. If user have access(is logged into stash) than source code from raw file is loaded.
If I trying same way, I getting respone:
XMLHttpRequest cannot load 'private_stash_file_link'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
EXCEPTION: Response with status: 0 for URL: null
Uncaught Response with status: 0 for URL: null
How can I handle this, cookies, specific options for get request, is it even possible?
EDIT 1.
Tried:
public getRawFile(link: string) {
let headers = new Headers();
headers.append('Access-Control-Allow-Headers', 'Content-Type');
headers.append('Access-Control-Allow-Methods', 'GET, OPTIONS');
headers.append('Access-Control-Allow-Origin', '*');
let options = new RequestOptions({headers: headers, withCredentials: true});
return this.http.get(link, options).map((res: Response) => res.text());
}
but same result for private repository..
plunker

The server that you are making the request to has to implement CORS to grant JavaScript from your website access (Cross Origin Resource Sharing (CORS)). So if you have access to the place where you are scraping, then add the following HTTP headers at the response of the receiving end:
Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *.example.com
Make sure to replace "*.example.com" with the domain name of the host that is sending the data/getting the data. Doing this should fix your problem.

Related

Error HTTP GET object list

I get an error when I try to retrieve a list of objects from a link (php server).
Blocking of a multi-origin request (cross-origin request): the "same
source" policy does not allow access to the remote resource located at
http: //localhost/eReport/index.php. Reason:
"Access-control-authorization-origin" token missing in the CORS
"Access-Control-Allow-Headers" CORS header.
I added a header like this tuto that is recommended on this link but I still have this error.
Can you help me please ?
My Service page:
#Injectable()
export class ReportService{
private baseUrl: string = 'http://localhost/report/reports.php';
constructor(private http : Http){}
getAll(): Observable<Report[]>{
let report$ = this.http
.get(`${this.baseUrl}`, { headers: this.getHeaders()})
.map(mapReports);
return report$;
}
private getHeaders(){
// I included these headers because otherwise FireFox
// will request text/html
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
return headers;
}
get(id: number): Observable<Report> {
let report$ = this.http
.get(`${this.baseUrl}/report/${id}`, {headers: this.getHeaders()})
.map(mapReport);
return report$;
}
My php page
header("Access-Control-Allow-Origin: *");
$tab = array(
array('id'=> '12', 'name'=> 'test','description' => '2018-04-01','url'=>'../../../assets/img/chat1.png' ),
array('id'=> '13', 'name'=> 'test','description' => '2018-04-01','url'=>'../../../assets/img/highcharts.png' )
);
echo json_encode($tab);
?>
Perhaps the quickest fix is to change your base url in the Angular app to /report/reports.php if the requests are going to the same server that served the app.
Your request is not working because when the client sends content of type application/json, the browser doesn't send the request right away. If you restart your browser then observe the network tab you will notice that instead of your GET, an OPTIONS request is first send, that includes headers similar to these:
Origin: yourserver
Access-Control-Request-Method: GET
Access-Control-Request-Headers: Content-Type, Accept
In this scenario, the browser expects the server to return not just the Access-Control-Allow-Origin header (which you're already doing), but all of these:
Access-Control-Allow-Origin: yourserver (or *)
Access-Control-Allow-Methods: GET (or a list eg: GET, POST, OPTIONS)
Access-Control-Allow-Headers: Content-Type, Accept (the same headers from above)
So you need to read the request headers from the previous block, and use their values when setting the response headers. If you have the apache_request_headers() method it's pretty easy. You can also get them from the $_SERVER superglobal.
// set required headers:
header("Access-Control-Allow-Origin: $_SERVER[HTTP_ORIGIN]");
header("Access-Control-Allow-Methods: $_SERVER[HTTP_ACCESS_CONTROL_REQUEST_METHOD]");
header("Access-Control-Allow-Headers: $_SERVER[HTTP_ACCESS_CONTROL_REQUEST_HEADERS]");
See this helpful article

Angular 2 access redmine Rest Api, no 'Access-Control-Allow-Origin'

I try to get issues from redmine via them Rest Api. When I call it from Postman I get response, but when I do it from my angular App I get such error
OPTIONS https://redmine.ourDomain.net/issues.json 404 (Not Found)
XMLHttpRequest cannot load https://redmine.ourDomain.net/issues.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 404.
Its how I do it in Angular
login(user: User): Observable<boolean> {
var headers: Headers = new Headers();
headers.append("Authorization", "Basic " + btoa(user.login + ":" + user.password));
let options = new RequestOptions({ headers: headers });
return this.http.get("https://redmine.ourDomain.net/issues.json", options)
.map((response: Response) => {
debugger;
if (response.status == 200) {
// set token property
// store username and jwt token in local storage to keep user logged in between page refreshes
localStorage.setItem('currentUser', JSON.stringify({ user }));
// return true to indicate successful login
return true;
} else {
// return false to indicate failed login
return false;
}
});
}
And there how request looks in my browser
You'll need to enable CORS access on the backend: http://www.redmine.org/plugins/redmine_cors
Here's a nice extension that will let you test frontend code outside of normal CORS restrictions. It's strictly for testing and won't help a production app, but nice to have: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi
CORS must be set up in the backend. Please note that is NOT a good practice to allow all origins Access-Control-Allow-Origin: '*' and that you will need to specify the other headers as well:
Access-Control-Allow-Methods: GET, OPTIONS
Access-Control-Allow-Headers: authorization.

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present

I Am not able to fetch data from Rest Server.Following Error is coming:
"Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access."
Response is coming as "0", This is not hitting the Rest Method also.
Rest APT:
#POST
#Timed
#Path("updateScore")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response updateScore(Player player)
{
StringBuilder returnStr = new StringBuilder("Sucess");
return Response.ok().
header("Access-Control-Allow-Origin", "http://localhost:8080").
header("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE, OPTIONS").
header("Access-Control-Allow-Headers", "Origin, Content-Type, X-Auth-Token").
allow("OPTIONS").
status(200).
entity("Hello").build();
}
JavaScript Call
var url = "http://192.168.0.101:9090/api/FGame/updateScore/";
var client = new XMLHttpRequest();
client.open('POST', url, true);
client.setRequestHeader('Content-Type', 'application/json');
client.send('{"Name" : 12}');
client.onreadystatechange = function() {
alert(client.status);
alert(client.data)
};
But if I am changing to JavaScript call as following then working fine.
JavaScript Call
var url = "http://192.168.0.101:9090/api/FGame/updateScore/";
var client = new XMLHttpRequest();
client.open('POST', url, true);
client.send(null);
client.onreadystatechange = function() {
alert(client.status);
alert(client.data)
};
In my scenario I am using an angular front-end Api to collect the data from a form object and a Java rest Api to write the data to a MySql database. But I was always having the "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource." error in the browser console. None of the suggested header modifications in the frontend like;
const headers: {
'Access-Control-Allow-Origin' : '*',
};
worked for me.
After hours of research in the internet one of my friends showed me the answer in not in the frontend but in the backend. Adding a WebConfig class to my java code fixed my problem.
#EnableWebMvc
#Configuration
public class WebConfig implements WebMvcConfigurer {
#Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("http://localhost:3000/", "http://localhost:4200/")
.allowedMethods("*")
.allowedHeaders("*");
}
}
Hope this finds those who is looking for an answer to the same error.

Access-Control-Allow-Origin not working in AngularJS application

I'm trying to consume my (CORS compatible) RESTful service
#Path("/greeting")
#GET
#Produces("application/json")
public Response greeting() {
String result = "{\"id\":1,\"content\":\"Hello, World!\"}";
return Response.ok() //200
.entity(result)
.header("Access-Control-Allow-Origin", "*")
.build();
}
from my AngularJS application.
function ($scope, $http) {
$scope.dashboard = "ESCO Dashboard";
console.log('start');
// Simple GET request example:
$http({
method: 'GET',
url: 'http://localhost:8080/NobelGrid/api/users/greeting'
}).then(function successCallback(response) {
console.log('success');
$scope.greeting = response.data;
}, function errorCallback(response) {
console.log('error');
});
console.log('end');
}
but I have this error:
XMLHttpRequest cannot load http://localhost:8080/NobelGrid/api/users/greeting. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
Using Console Network of Chrome this seems true cause the Response Header is:
Anyway accessing to the REST service from the browser and not from the Angular app, the header is correct
I also tried this tutorial:
https://spring.io/guides/gs/consuming-rest-angularjs/
with their RESTful service (also CORS compatible, they said), but the result is the same.
ps: I'm using WebStorm as IDE.
UPDATE - SOLVED
Writing this handler at server-side:
#Path("/greeting")
#OPTIONS
#Produces("application/json")
public Response greetingOPT() {
return Response.status(200) //200
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT, OPTIONS")
.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, X-Codingpedia,Authorization")
.build();
}
it works. At the beginning it gives to me another error:
Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight [..]
but adding Authorization to the Access-Control-Allow-Headers of the GET and POST resolve the problem.
Look at the error message:
Response to preflight request
Look at the Network log:
Request Method: OPTIONS
Look at your API:
#GET
You need to write a handler for the preflight OPTIONS request before the browser will make the GET request to the handler you have written.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:1111' is therefore not allowed access

I have a situation I can't really understand. Two computers, in one I'm using brackets for my Web development, in the other (Linux) I'm running Tomcat (7). Both are within the same LAN (and hence same address range). I'm getting the error shown in the title and hence I'm completely stuck. Tried the following code with no success:
var req = { url: l_url, method:"POST", headers: {
'Content-Type': 'application/x-www-form-urlencoded' ,
// 'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Origin': 'http://127.0.0.1',
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, application/x-www-form-urlencoded'
}, data: l_params } ;
$http(req).
success(function(data, status, headers, config) {
console.log("DB_Services - Success; data is: " + JSON.stringify(data)) ;
l_deferred.resolve(data);
}).
error(function(data, status, headers, config) {
console.log("DB_Services - Error: " + data) ;
l_deferred.reject(status);
});
return l_deferred.promise;
The error (Chrome's console) reads: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:58275' is therefore not allowed access.
My search brought me to the conclusion (not sure it is correct) that the Tomcat is rejecting the request, even though I included the above shown heading details.
I also found that it is possible to tell Tomcat to allow the request, but don't know how and where to configure that.
So, my questions are:
1) Is my http request properly phrased?
2) How do I make Tomcat to allow this request?
Thanks in advance for any suggestion.
You could try adding a filter class to your java code in the server side, sample code
public class CorsFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
response.addHeader("Access-Control-Allow-Origin", "*");
if (request.getHeader("Access-Control-Request-Method") != null && "OPTIONS".equals(request.getMethod())) {
//Add CORS "pre-flight" request
response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "Authentication-token");
response.addHeader("Access-Control-Allow-Headers", "Content-Type");
response.addHeader("Access-Control-Max-Age", "3600");
}
filterChain.doFilter(request, response);
}
}
add it to web.xml
<filter>
<filter-name>cors</filter-name>
<filter-class>location.of.filter.class</filter-class>
</filter>
<filter-mapping>
<filter-name>cors</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
and in in your angular js app config try adding
app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
this had solved my problem, hope it will help you too.
You are running into what's known as the Same-Origin Policy. One of the core motives behind this policy is to prevent scripts that you didn't write (and thus are untrusted) from running on your page (and possibly taking data from it). Scripts that attempt to do that maliciously are doing what is known as Cross-Site Scripting.
To not run afoul of the Same-Origin Policy, your site must only ask for scripts from:
A site with the same protocol as your site
A site with the same hostname as your site
A site with the same port as your site
You'll notice this basically means only your site.
One newer method of getting around this restriction is to use Cross-Origin Resource Sharing (CORS). To do this you must have control of the code/servers for all the scripts you would like to run.
There is already good SO question/answer to get you started: Ways to circumvent the same-origin policy

Categories