I would like to know your opinion on the issue in this simple code in ajax, which has the problem Access-Control-Allow-Origin, already tried several ways defenir the ember "Access-Control-Allow-Origin": "* " but without success, so I wonder if someone with the same problem found a solution.
I use the url address localhost: 4200 and already tried with a subdomain of firebase in both cases the error was always the same.
The ajax request:
import Ember from 'ember';
import { isAjaxError, isNotFoundError, isForbiddenError } from 'ember-ajax/errors';
export default Ember.Controller.extend({
ajax: Ember.inject.service(),
actions: {
code() {
var cliente = '***';
var redirectUri = 'http://localhost:4200/teste';
var client_secret = '***';
var code = '***';
var grant_type = 'authorization_code';
var data =
"client_id=" + cliente +
"&redirect_uri=" + encodeURIComponent(redirectUri) +
"&client_secret=" + client_secret +
"&code=" + code +
"&grant_type=" + grant_type;
this.send('post', data)
},
post(data) {
this.get('ajax').post("https://login.live.com/oauth20_token.srf", {
method: 'POST',
headers: {
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/x-www-form-urlencoded",
},
data: data,
dataType: 'JSON',
});
},
}});
My content Security Policy:
contentSecurityPolicy: {
'connect-src': "'self' http://localhost:4200 https://*.googleapis.com https://login.live.com/oauth20_token.srf",
'child-src': "'self' http://localhost:4200",
'script-src': "'self' 'unsafe-eval' https://login.live.com",
'img-src': "'self' https://*.bp.blogspot.com https://cdn2.iconfinder.com http://materializecss.com https://upload.wikimedia.org https://www.gstatic.com",
'style-src': "'self' 'unsafe-inline' ",
},
The error is:
XMLHttpRequest cannot load https://login.live.com/oauth20_token.srf. 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:4200' is therefore not allowed access.
This doesn't actually seem like an Ember related question. The problem you are having is exclusively backend related. For ajax requests to work backend should serve the proper 'Access-Control-Allow-Origin' header in response. Otherwise your browser would not accept such responses and throw an error that you are seeing. It's not Ember related in any way it's just how browsers work.
Now to fix this issue you would have to add the proper client server name to your backend 'Access-Control-Allow-Origin' headers. I.e. if you are going to serve your Ember app from https://example.com that is what you need to add to 'Access-Control-Allow-Origin' header.
So let's assume you just want the ways to bypass this messages.
There are plenty of browser extensions that would disable CORS check in your browser for development. This way would work just fine if you are using localhost but plan to move to real server in the future and have a way to actually set 'Access-Control-Allow-Origin' header on backend.
Let's assume you don't have any way to change the backend header now but desperately want to test how the client app would work on your remote https://example.com. You would have to setup a remote server to proxy all your requests to the target backend modifying the headers that are sent in response so your browser would accept them. This way you don't have to use any chrome extensions to disable CORS.
One of the simplest ways to setup such server would be to use the following package - https://www.npmjs.com/package/express-http-proxy . The configuration for your case would be pretty straightforward.
sample express app:
var proxy = require('express-http-proxy');
var app = require('express')();
app.use('/', proxy('www.example.com', {
intercept: function (rsp, data, req, res, callback) {
res.append('Access-Control-Allow-Origin', '*');
callback(null, data);
}}));
app.listen(3000, function () {
console.log('listening on port 3000');
});
Related
I'm new at ReactJS but I'm trying to learn by myself now. I'm facing a problem when I try to add data do may Database, in my RestAPI with MongoDB, using fetch function on my web Application. When I click my button, it runs the following code:
SubmitClick(){
//console.log('load Get User page'); //debug only
fetch('http://localhost:4000/users/', {
method: 'POST',
headers: {
'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: 'deadpool#gmail.com',
first_name: 'Wade',
last_name: 'Wilson',
personal_phone: '(11) 91111-2222',
password: 'wolv3Rine'
})
})
//this.props.history.push('/get'); //change page layout and URL
}
and I get the following message on my browser:
OPTIONS http://localhost:4000/users/ 401 (Unauthorized)
Failed to load http://localhost:4000/users/: 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 401. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
Uncaught (in promise) TypeError: Failed to fetch
My RestAPI have Basic Auth, but i don't know what i'm supposed to insert in headers to have access. I got this 'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=', from Postman, when I configured the Authorization tab, and it was automatically added to the headers.
I'm using Google Chrome as my default browser.
My backend code is the following:
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
var basicAuth = require('express-basic-auth')
const app = express();
mongoose.connect('mongodb://localhost/usersregs', { useMongoClient: true });
mongoose.Promise = global.Promise;
app.use(basicAuth({
users: {
'admin': 'supersecret',
'adam': 'password1234',
'eve': 'asdfghjkl'
}
}))
app.use(bodyParser.json());
app.use(function(err, req, res, next){
console.log(err);
//res.status(450).send({err: err.message})
});
app.use(require('./routes/api'));
app.listen(4000, function(){
console.log('Now listening for request at port 4000');
});
It may not be the same problem as the OP, but I was able to get basic auth protected fetches working just by adding a credentials mode...
fetch(
'http://example.com/api/endpoint',
{ credentials: "same-origin" }
)
See here: https://github.github.io/fetch/ under Request > Options
You're trying to access port 4000 (your API, or backend) from port 3000 (Your client). This violates the Same-origin policy, even though you're clearly running both the client and the API from the same machine.
To get around this the easiest way is to just fire up your client from the same port as your API (port 4000) this should allow your host to see that you're trying to access resources from the same domain/port which won't force a preflight request.
If that's not possible you'll have to configure CORS for your API, and this question doesn't give any details about the backend so I can't instruct you on how to do that at the moment.
And of course this approach obviously won't work if you're running two separate servers in production, but that's probably outside of the scope of this question.
I'm calling this function from my asp.net form and getting following error on firebug console while calling ajax.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://anotherdomain/test.json. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
var url= 'http://anotherdomain/test.json';
$.ajax({
url: url,
crossOrigin: true,
type: 'GET',
xhrFields: { withCredentials: true },
accept: 'application/json'
}).done(function (data) {
alert(data);
}).fail(function (xhr, textStatus, error) {
var title, message;
switch (xhr.status) {
case 403:
title = xhr.responseJSON.errorSummary;
message = 'Please login to your server before running the test.';
break;
default:
title = 'Invalid URL or Cross-Origin Request Blocked';
message = 'You must explictly add this site (' + window.location.origin + ') to the list of allowed websites in your server.';
break;
}
});
I've done alternate way but still unable to find the solution.
Note: I've no server rights to make server side(API/URL) changes.
This happens generally when you try access another domain's resources.
This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).
The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the resources.
You can fix this problem if you are the owner of both domains:
Solution 1: via .htaccess
To change that, you can write this in the .htaccess of the requested domain file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
If you only want to give access to one domain, the .htaccess should look like this:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin 'https://my-domain.example'
</IfModule>
Solution 2: set headers the correct way
If you set this into the response header of the requested file, you will allow everyone to access the resources:
Access-Control-Allow-Origin : *
OR
Access-Control-Allow-Origin : http://www.my-domain.example
Server side put this on top of .php:
header('Access-Control-Allow-Origin: *');
You can set specific domain restriction access:
header('Access-Control-Allow-Origin: https://www.example.com')
in your ajax request, adding:
dataType: "jsonp",
after line :
type: 'GET',
should solve this problem ..
hope this help you
If you are using Express js in backend you can install the package cors, and then use it in your server like this :
const cors = require("cors");
app.use(cors());
This fixed my issue
This worked for me:
Create php file that will download content of another domain page without using js:
<?
//file name: your_php_page.php
echo file_get_contents('http://anotherdomain/test.json');
?>
Then run it in ajax (jquery). Example:
$.ajax({
url: your_php_page.php,
//optional data might be usefull
//type: 'GET',
//dataType: "jsonp",
//dataType: 'xml',
context: document.body
}).done(function(data) {
alert("data");
});
You have to modify your server side code, as given below
public class CorsResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
}
}
You must have got the idea why you are getting this problem after going through above answers.
self.send_header('Access-Control-Allow-Origin', '*')
You just have to add the above line in your server side.
In a pinch, you can use this Chrome Extension to disable CORS on your local browser.
Allow CORS: Access-Control-Allow-Origin Chrome Extension
I'm calling this function from my asp.net form and getting following error on firebug console while calling ajax.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://anotherdomain/test.json. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
var url= 'http://anotherdomain/test.json';
$.ajax({
url: url,
crossOrigin: true,
type: 'GET',
xhrFields: { withCredentials: true },
accept: 'application/json'
}).done(function (data) {
alert(data);
}).fail(function (xhr, textStatus, error) {
var title, message;
switch (xhr.status) {
case 403:
title = xhr.responseJSON.errorSummary;
message = 'Please login to your server before running the test.';
break;
default:
title = 'Invalid URL or Cross-Origin Request Blocked';
message = 'You must explictly add this site (' + window.location.origin + ') to the list of allowed websites in your server.';
break;
}
});
I've done alternate way but still unable to find the solution.
Note: I've no server rights to make server side(API/URL) changes.
This happens generally when you try access another domain's resources.
This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).
The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the resources.
You can fix this problem if you are the owner of both domains:
Solution 1: via .htaccess
To change that, you can write this in the .htaccess of the requested domain file:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
If you only want to give access to one domain, the .htaccess should look like this:
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin 'https://my-domain.example'
</IfModule>
Solution 2: set headers the correct way
If you set this into the response header of the requested file, you will allow everyone to access the resources:
Access-Control-Allow-Origin : *
OR
Access-Control-Allow-Origin : http://www.my-domain.example
Server side put this on top of .php:
header('Access-Control-Allow-Origin: *');
You can set specific domain restriction access:
header('Access-Control-Allow-Origin: https://www.example.com')
in your ajax request, adding:
dataType: "jsonp",
after line :
type: 'GET',
should solve this problem ..
hope this help you
If you are using Express js in backend you can install the package cors, and then use it in your server like this :
const cors = require("cors");
app.use(cors());
This fixed my issue
This worked for me:
Create php file that will download content of another domain page without using js:
<?
//file name: your_php_page.php
echo file_get_contents('http://anotherdomain/test.json');
?>
Then run it in ajax (jquery). Example:
$.ajax({
url: your_php_page.php,
//optional data might be usefull
//type: 'GET',
//dataType: "jsonp",
//dataType: 'xml',
context: document.body
}).done(function(data) {
alert("data");
});
You have to modify your server side code, as given below
public class CorsResponseFilter implements ContainerResponseFilter {
#Override
public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
throws IOException {
responseContext.getHeaders().add("Access-Control-Allow-Origin","*");
responseContext.getHeaders().add("Access-Control-Allow-Methods", "GET, POST, DELETE, PUT");
}
}
You must have got the idea why you are getting this problem after going through above answers.
self.send_header('Access-Control-Allow-Origin', '*')
You just have to add the above line in your server side.
In a pinch, you can use this Chrome Extension to disable CORS on your local browser.
Allow CORS: Access-Control-Allow-Origin Chrome Extension
I am trying to use the Cloudinary REST API, but the client libraries provided are not useful for my purpose.
So the settings I use are:
api_key = '111111111111111';
api_secret = 'fdgdsfgsdfgsdfgsdfgsdfg';
my_authorization = 'Basic ' + window.btoa(this.api_key + ':' + this.api_secret);
url_base = 'http://api.cloudinary.com/api/v1_1';
cloud_name = '/http-mysite-com';
connect_method = 'GET';
tag_list = '/tags/image';
I make the call with something similar to this:
request(tag_list) {
connection.request({
method: connect_method,
url: url_base + cloud_name + service_url,
headers: {
'Authorization': authorization,
'Content-Type': 'application/json'
}
}).then(function(response) {
// triumph
}, function(er) {
// all is lost
});
};
The response is this:
XMLHttpRequest cannot load
http://api.cloudinary.com/api/v1_1/http-mysite-com/tags/image. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://myhost:8000' is therefore not allowed
access. The response had HTTP status code 404.
What am I doing wrong?
Thanks
PS I also tried using 'https' instead of 'http', as the documentation recommends. In that case I get back:
XMLHttpRequest cannot load
https://api.cloudinary.com/v1_1/http-mysite-com/tags/image. The
request was redirected to
'http://api.cloudinary.com/api/v1_1/http-mysite-com/tags/image',
which is disallowed for cross-origin requests that require preflight.
Admin API calls use your api_secret which should not be revealed in your client-side code. That's why Cloudinary doesn't support CORS headers for the Admin API.
Therefore, Admin API calls should be performed on the server-side only.
I have two app with nodejs and angularjs.nodejs app has some code like this :
require('http').createServer(function(req, res) {
req.setEncoding('utf8');
var body = '';
var result = '';
req.on('data', function(data) {
// console.log("ONDATA");
//var _data = parseInput( data,req.url.toString());
var _data = parseInputForClient(data, req.url.toString());
switch (req.url.toString()) {
case "/cubes":
{
and this app host on http://localhost:4000.angularjs app host with node http-server module on localhost://www.localhost:3030.in one of my angularjs service i have some thing like this :
fetch:function(){
var data = '{somedata:"somedata"}';
return $http.post('http://localhost:4000/cubes',data).success(function(cubes){
console.log(cubes);
});
}
but when this service send a request to server get this error:
XMLHttpRequest cannot load http://localhost:4000/cubes. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3030' is therefore not allowed access.
so i search the web and stackoverflow to find some topic and i find this and this . according to these topics i change the header of response in the server to something like this :
res.writeHead(200, {
'Content-Type': 'application/json',
"Access-Control-Allow-Origin": "*"
});
res.end(JSON.stringify(result));
but this dose'nt work.I try with firefox,chrome and also check the request with Telerik Fiddler Web Debugger but the server still pending and i get the Access Control Allow Origin error.
You do POST request, which generates preflight request according to CORS specification: http://hacks.mozilla.org/2009/07/cross-site-xmlhttprequest-with-cors/ and https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
Your server should also respond to OPTIONS method (besides POST), and return Access-Control-Allow-Origin there too.
You can see it's the cause, because when your code creates request in Network tab (or in Fiddler proxy debugger) you should see OPTIONS request with ORIGIN header