Add Cors Header to an Http Request Using Ajax

How to get a cross-origin resource sharing (CORS) post request working

I finally stumbled upon this link "A CORS POST request works from plain javascript, but why not with jQuery?" that notes that jQuery 1.5.1 adds the

 Access-Control-Request-Headers: x-requested-with

header to all CORS requests. jQuery 1.5.2 does not do this. Also, according to the same question, setting a server response header of

Access-Control-Allow-Headers: *

does not allow the response to continue. You need to ensure the response header specifically includes the required headers. ie:

Access-Control-Allow-Headers: x-requested-with 

Cors header error with ajax request request

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading of resources. So you must add permission to client side(ajax request) to receive response from server side.

You can handle this issue by creating a new middleware:

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
// Cors middleware for allow api access from client side 'vue project'
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin','*')
->header('Access-Control-Allow-Methods','*')
->header('Access-Control-Allow-Headers','*')
;
}
}

and register the new middleware in kernel.php:
in middleware array add:

protected $middleware = [
\App\Http\Middleware\Cors::class,
];

in route middleware array add:

protected $routeMiddleware = ['cors' => \App\Http\Middleware\Cors::class,
];

Finally implement this middleware into routes:

Route::group(['middleware' => ['cors']], function () {
//... your routes
});

As a result when adding:
->header('Access-Control-Allow-Origin','*')
it means that you allow any other origin to access your app. You could just add an array of specific routes which you want to access your app. In your case I think it's ['127.0.0.1:8000']

Enabling CORS in .ajax POST

I have the same problem, I solved this issue at my server side code, not in the ajax request. in my case; I am using cakePHP at server side.

I added this code to my php controller.

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept");

How to add custom header for Ajax CORS request

If your web server is Apache

Add the following in .htaccess file and place it in root directory of your application(http://api.test)

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "POST"

For IIS7

Create Web.config file on the root directory of your application and add the following XML code in it

<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>

Add CORS header to an http request using Ajax

You can't authorize yourself like that. It's a response header; details in the specification. The server you're sending the request to has to send that header back to let the browser know it's okay to allow your page to send an ajax request to that server. There's nothing you can do in your client-side code if the server you're trying to request from doesn't allow your origin.

Allow headers in cross-domain ajax request

It seems that each header must explicitly be listed and I added x-test-header to Access-Control-Allow-Headers.

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Header set Access-Control-Allow-Headers "x-test-header, Origin, X-Requested-With, Content-Type, Accept"

AJAX request gets No 'Access-Control-Allow-Origin' header is present on the requested resource error

This is by design. You can't make an arbitrary HTTP request to another server using XMLHttpRequest unless that server allows it by putting out an Access-Control-Allow-Origin header for the requesting host.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

You could retrieve it in a script tag (there isn't the same restriction on scripts and images and stylesheets), but unless the content returned is a script, it won't do you much good.

Here's a tutorial on CORS:

http://www.bennadel.com/blog/2327-cross-origin-resource-sharing-cors-ajax-requests-between-jquery-and-node-js.htm

This is all done to protect the end user. Assuming that an image is actually an image, a stylesheet is just a stylesheet and a script is just a script, requesting those resources from another server can't really do any harm.

But in general, cross-origin requests can do really bad things. Say that you, Zoltan, are using coolsharks.com. Say also that you are logged into mybank.com and there is a cookie for mybank.com in your browser. Now, suppose that coolsharks.com sends an AJAX request to mybank.com, asking to transfer all your money into another account. Because you have a mybank.com cookie stored, they successfully complete the request. And all of this happens without your knowledge, because no page reload occurred. This is the danger of allowing general cross-site AJAX requests.

If you want to perform cross-site requests, you have two options:

  1. Get the server you are making the request to to either

    a. Admit you by putting out a Access-Control-Allow-Origin header that includes you (or *)

    b. Provide you with a JSONP API.

or


  1. Write your own browser that doesn't follow the standards and has no restrictions.

In (1), you must have the cooperation of the server you are making requests to, and in (2), you must have control over the end user's browser. If you can't fulfill (1) or (2), you're pretty much out of luck.

However, there is a third option (pointed out by charlietfl). You can make the request from a server that you do control and then pass the result back to your page. E.g.

<script>
$.ajax({
type: 'GET',
url: '/proxyAjax.php?url=http%3A%2F%2Fstackoverflow.com%2F10m',
dataType: 'text/html',
success: function() { alert("Success"); },
error: function() { alert("Error"); }
});
</script>

And then on your server, at its most simple:

<?php
// proxyAjax.php
// ... validation of params
// and checking of url against whitelist would happen here ...
// assume that $url now contains "http://stackoverflow.com/10m"
echo file_get_contents($url);

Of course, this method may run into other issues:

  • Does the site you are a proxy for require the correct referrer or a certain IP address?
  • Do cookies need to be passed through to the target server?
  • Does your whitelist sufficiently protect you from making arbitrary requests?
  • Which headers (e.g. modify time, etc) will you be passing back to the browser as your server received them and which ones will you omit or change?
  • Will your server be implicated as having made a request that was unlawful (since you are acting as a proxy)?

I'm sure there are others. But if none of those issues prevent it, this third method could work quite well.

CORS preflight requests working with jQuery AJAX, but failing with native XmlHttpRequests in Firefox

After some more research I finally found out that this is actually a firefox-related issue with userscripts: https://bugzilla.mozilla.org/show_bug.cgi?id=1715249



Related Topics



Leave a reply



Submit