i have this code:
net.requestXHR = function() {
this.xhr = null;
if(window.XMLHttpRequest === undefined) {
window.XMLHttpRequest = function() {
try {
// Use the latest version of the activex object if available
this.xhr = new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch(e1) {
try {
// Otherwise fall back on an older version
this.xhr = new ActiveXObject("Mxsml2.XMLHTTP.3.0");
}
catch(e2) {
//Otherwise, throw an error
this.xhr = new Error("Ajax not supported in your browser");
}
}
};
}
else
this.xhr = new XMLHttpRequest();
}
net.requestXHR.prototype.post = function(url, data) {
if(this.xhr != null) {
this.xhr.open("POST", url);
this.xhr.setRequestHeader("Content-Type", "application/json");
this.xhr.send(data);
}
}
var rs = new net.requestSpeech();
console.log(JSON.stringify(interaction));
rs.post("http://localhost:8111", JSON.stringify(interaction));
when the send execute, i have this log:
OPTIONS http://localhost:8111/ [HTTP/1.1 405 Method Not Allowed 74ms]
And in localhost:8111 i have a reslet serverResource that accept post, it is problem of same origin policy? i have modify the restlet to put the allow-origin header and i test it with another GET http request (in jquery) and work ok. I have the problem of same origin resolve because i use an html5 browser and my server put the headers in the response, so why the send shows me this error? why change POST for OPTION?
Thanks!
Possible duplicate?: I think no, but it's true, the problem is the
same for both questions, but mine are refers since the question that
there is an issue with the browser, and the other, first points to
jquery. By experience the time does not count for duplicate, the
answers are different but it's true that both questions complement
each other.
Yes, this is a "problem with same-origin policy". You are making your request either to a different server or to a different port, meaning that it is a cross-site HTTP request. Here is what the documentation has to say about such requests:
Additionally, for HTTP request methods that can cause side-effects on
server's data (in particular, for HTTP methods other than GET, or for
POST usage with certain MIME types), the specification mandates that
browsers "preflight" the request, soliciting supported methods from
the server with an HTTP OPTIONS request method, and then, upon
"approval" from the server, sending the actual request with the actual
HTTP request method.
There is a more detailed description in the CORS standard ("Cross-Origin Request with Preflight" section). Your server needs to allow the OPTIONS request and send a response with Access-Control-Allow-Origin, Access-Control-Allow-Headers and Access-Control-Allow-Methods headers allowing the request. Then the browser will make the actual POST request.
I was having this exact problem from a JavaScript code that sent an ajax content.
In order to allow the Cross-Origin Request with Preflight I had to do this in the .ASPX that was receiving the petition:
//Check the petition Method
if (Request.HttpMethod == "OPTIONS")
{
//In case of an OPTIONS, we allow the access to the origin of the petition
string vlsOrigin = Request.Headers["ORIGIN"];
Response.AddHeader("Access-Control-Allow-Origin", vlsOrigin);
Response.AddHeader("Access-Control-Allow-Methods", "POST");
Response.AddHeader("Access-Control-Allow-Headers", "accept, content-type");
Response.AddHeader("Access-Control-Max-Age", "1728000");
}
You have to be careful and check what headers are being asked by your petition. I checked those using Fiddler.
Hope this serves someone in the future.
Answer:
Your browser is initiating a PreFlight OPTIONS request.
Why:
Because your request is not a simple request.
Why it is not a simple request:
Because of "Content-Type" = "application/json".
Solution:
Try to use either of below content types :
application/x-www-form-urlencoded
multipart/form-data
text/plain
As others have pointed out, this is a CORS thing.
This is how to handle it in NGINX (based on this source):
location / {
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "http://example.com";
add_header Access-Control-Allow-Methods "GET, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization";
add_header Access-Control-Allow-Credentials "true";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
}
If you want to allow CORS requests from any origin, replace,
add_header Access-Control-Allow-Origin "http://example.com";
with
add_header Access-Control-Allow-Origin "*";
If you don't use authorization, you won't need this bit:
add_header Access-Control-Allow-Headers "Authorization";
add_header Access-Control-Allow-Credentials "true";
For the API I'm developing I needed to whitelist 3 request methods: GET, POST and OPTIONS, and an X-App-Id header, so this us what I ended up doing:
if ($request_method = OPTIONS ) {
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET, POST, OPTIONS";
add_header Access-Control-Allow-Headers "X-App-Id";
add_header Content-Length 0;
add_header Content-Type text/plain;
return 200;
}
Related
im making an api using Javalin and trying to send data to it from javascript, however i get cors errors whenever i try to do so. i can recieve data just fine but not send data. Here is my error: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
-----------javascript-----------
function sendOurAjax(){
console.log("ajax using fetch")
let ourCustomSuper = {
"name": "SpaceMonkey",
"superpower": "person atmosphere",
"bounty": 0
}
fetch(`http://localhost:8000/api`, {
method: "post",
'headers': {
'Content-Type': 'application/json',
'BARNACLES': 'custom header value'
},
'body': JSON.stringify(ourCustomSuper)
})
.then(
function(daResponse){
console.log(daResponse);
const convertedResponse = daResponse.json();
return convertedResponse;
}
).then(
function(daSecondResponse){
console.log("Fetch is a thing. We did it.");
console.log(daSecondResponse);
}
).catch(
(stuff) => {console.log("this sucker exploded")}
)
}
-----------java-----------
app.get("/api", context ->{
context.header("Access-Control-Allow-Origin", "*");
context.header("Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS");
context.header("Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token");
System.out.println("The endpoint method has fired");
context.result("endpoint handler has fired");
context.json(myList);
});
Why was the CORS error there in the first place?
The error stems from a security mechanism that browsers implement called the same-origin policy.
The same-origin policy fights one of the most common cyber attacks out there: cross-site request forgery. In this maneuver, a malicious website attempts to take advantage of the browser’s cookie storage system.
For every HTTP request to a domain, the browser attaches any HTTP cookies associated with that domain. This is especially useful for authentication, and setting sessions. For instance, it’s feasible that you would sign into a web app like facebook-clone.com. In this case, your browser would store a relevant session cookie for the facebook-clone.com domain:
here a link on the cors subject
How To Fix CORS Error
Offhand is see you do have the
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://localhost:3000
set but the content type might be wrong i.e json
something along the lines of
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Content-Type: application/json
I would like to make a XmlHttp GET request from client Javascript to a Apache SVN endpoint and I'm facing the following error:
Failed to load http://IP_ADDRESS/svn/: Response to preflight request
doesn't pass access control check: No 'Access-Control-Allow-Origin'
header is present on the requested resource. Origin
'http://IP_ADDRESS:3000' is therefore not allowed access.
I've tried set the Header set Access-Control-Allow-Origin "*" in the following files and no success so far.
/etc/apache2/mods-available/dav_svn.conf (the configuration is inside this file)
.htaccess (inside the endpoint root folder)
I'm running out of ideias how to do it.
The Javascript request code:
var xmlhttp = new XMLHttpRequest();
// encodedData = ...
xmlhttp.open('GET', url, true);
xmlhttp.setRequestHeader("Authorization", "Basic " + encodedData);
xmlhttp.withCredentials = true;
xmlhttp.send();
What am I doing wrong?
Have you tried adding the address of the client instead of *?
Header set Access-Control-Allow-Origin "http://IP_ADDRESS:3000"
Also if it doesn't work I would suggest adding these other options:
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Methods "POST,GET,OPTIONS,PUT,DELETE"
Header set Access-Control-Allow-Headers "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
I'm hosting a website that has a number of different domain names pointing at it.
lets call the hosted website example.com and the url-forwarded domain names - example-x.com, example-y.com, example-z.com
When the url-forwarded domains are visited, cross domain requests are made back to the host site, example.com.
I'm currently making ajax GET requests to json files and receiving the following error;
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://example-x.com' is therefore not allowed
access.
Even though the preflight OPTIONS return a status of 200 and the GET method returns a status of 200.
OPTIONS;
GET
I have set the following CORs headers on the host htaccess;
# <IfModule mod_headers.c>
SetEnvIfNoCase Origin "https?://(www\.)?(example-x\.com|example-y\.com|example-z\.com)(:\d+)?$" ACAO=$0
Header set Access-Control-Allow-Origin %{ACAO}e env=ACAO
Header set Access-Control-Allow-Methods "GET, PUT, POST, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range"
Header set Access-Control-Allow-Credentials true
# </IfModule>
And i'm call GET using the following ajax request;
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
var url = 'http://example.com/data.json';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader("Content-Type", "application/json; charset=UTF-8");
xhr.setRequestHeader('Accept', 'application/json, text/javascript');
xhr.onload = function() { console.log('success');};
xhr.onerror = function() { console.log('error'); };
xhr.send();
EDIT
Removing setRequestHeader("Content-Type", "application/json; charset=UTF-8") from the ajax request has removed the preflight requirement, however the CORs error still persists, the screenshot below shows the request / response of GET, its my guess that the correct htaccess headers have not been set on the RequestURL - http://example.com/cms/wp-content/uploads/2017/04/preloader_data.json
GET - WITHOUT OPTIONS PREFLIGHT
You are trying to retrieve a json by a GET request. This should be a simple request, and it does not need to have a preflight request.
If you look at the requirements for a preflight request from MDN, you can see that setting Content-Type other than application/x-www-form-urlencoded, multipart/form-data or text/plain will cause this preflighted request.
If you look at the content-type from the RFC, it is a "SHOULD" for "a message containing a payload body". But your get request does not have a payload. As a result remove that header from your ajax call.
I am trying to Make an ajax request using fetch, and when I do, I get a 405 (Method Not Allowed) error.
I am executing it like this:
fetch(url, {
method: 'get',
headers: {
'Game-Token': '123'
}
});
And that is giving me an error. If I remove the headers, the request goes through. However, I need that header for validation on the server.
fetch(url, { method: 'get' });
I have the following setup in my .htaccess file:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS, FETCH"
Header set Access-Control-Allow-Credentials "true"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept, Authorization, X-CSRF-TOKEN, Game-Token, developerKey"
Header set X-Frame-Options "SAMEORIGIN"
Header set Access-Control-Expose-Headers "Game-Token"
I am not sure what is causing this to not go through.
So, this had nothing to do with JavaScript or the .htaccess. Instead it has to do with Lumen. We need to catch the OPTIONS request and reply back. What we did was create a middleware file that checked for the OPTIONS method and responds with a 200.
use Closure;
class CorsMiddleware
{
public function handle($request, Closure $next)
{
if ($request->isMethod('OPTIONS'))
{
return response('',200);
}
return $next($request);
}
}
I built an API with the SLIM Micro-Framework. I setup some middleware that adds the CORS headers using the following code.
class Cors{
public function __invoke(Request $request, Response $response, $next){
$response = $next($request, $response);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
For my front-end, I used VueJS. I setup VueResource and created a function with the following code.
register (context, email, password) {
Vue.http({
url: 'api/auth/register',
method: 'POST',
data: {
email: email,
password: password
}
}).then(response => {
context.success = true
}, response => {
context.response = response.data
context.error = true
})
}
In chrome, the following error is logged to the console.
XMLHttpRequest cannot load http://mysite:9800/api/auth/register. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite' is therefore not allowed access.
Oddly enough, GET requests work perfectly.
You half 1/2 the solution here.
What you are missing is an OPTIONS route where these headers need to be added as well.
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
This happens because preflight request is of OPTIONS type. You need to make an event listener on your request, which checks the type and sends a response with needed headers.
Unfortunately i don't know Slim framework, but here's the working example in Symfony.
First the headers example to be returned:
// Headers allowed to be returned.
const ALLOWED_HEADERS = ['Authorization', 'Origin', 'Content-Type', 'Content-Length', 'Accept'];
And in the request listener, there's a onKernelRequest method that watches all requests that are coming in:
/**
* #param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
// Don't do anything if it's not the master request
if (!$event->isMasterRequest()) {
return;
}
// Catch all pre-request events
if ($event->getRequest()->isMethod('OPTIONS')) {
$router = $this->container->get('router');
$pathInfo = $event->getRequest()->getPathInfo();
$response = new Response();
$response->headers->set('Access-Control-Allow-Origin', $event->getRequest()->headers->get('Origin'));
$response->headers->set('Access-Control-Allow-Methods', $this->getAllowedMethods($router, $pathInfo));
$response->headers->set('Access-Control-Allow-Headers', implode(', ', self::ALLOWED_HEADERS));
$response->headers->set('Access-Control-Expose-Headers', implode(', ', self::ALLOWED_HEADERS));
$response->headers->set('Access-Control-Allow-Credentials', 'true');
$response->headers->set('Access-Control-Max-Age', 60 * 60 * 24);
$response->send();
}
}
Here i just reproduce the Origin (all domains are allowed to request the resource, you should probably change it to your domain).
Hope it will give some glues.
Actually CORS is implemented at browser level. and Even with
return $response
->withHeader('Access-Control-Allow-Origin', 'http://mysite')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
chrome and Mozilla will not set headers to allow cross origin. So, you need forcefully disable that..
Read more about disabling CORS
Disable same origin policy in Chrome
CORS can be hard to config. The key is that you need to set the special headers in your server and your client, and I don't see any Vue headers set, besides as far as I know http is not a function. However here is some setup for a post request.
const data = {
email: email,
password: password
}
const options = {
headers: {
'Access-Control-Expose-Headers': // all of your headers,
'Access-Control-Allow-Origin': '*'
}
}
Vue.http.post('api/auth/register', JSON.stringify(data), options).then(response => {
// success
}, response => {
// error
})
Notice that you need to stringify your data and you need to expose your headers, usually including the Access-Control-Allow-Origin header.
What I did in one of my own apps was to define interceptors so I don't worry to set headers for every request.
Vue.http.headers.common['Access-Control-Expose-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, x-session-token, timeout, Content-Length, location, *'
Vue.http.headers.common['Access-Control-Allow-Origin'] = '*'