my scenario is composed by two webserver one local and one remote.
Local webserver (Apache) process a web app in which I want make an ajax request to remote webserver (Lighttpd).
Ajax request use angularjs $http.
var req = {
method: 'POST',
url: 'http://url/myphp.php',
headers: {
'Authorization': 'Basic ' + btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
},
xhrFields: {
withCredentials: true
},
crossDomain: true,
data: xmlString
}
$http(req).then(function () {
console.log("OK!");
});
Remote php script is:
<?php
echo "You have CORS!";
?>
Unfortunately I got a
401 Unhauthorized
XMLHttpRequest cannot load http://url/myphp.php. 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:8888' is therefore not allowed access. The response had HTTP status code 401.
Remote web server has .htpasswd authentication mode enable and CORS request configured.
Follow a piece of lighttpd.conf
setenv.add-response-header = ( "Access-Control-Allow-Origin" => "*" )
For add-response-header to work in lighttpd you must enable mod_setenv in your server.modules. However, you have to enable this mod_setenv before mod_status.
server.modules = (
# ...
"mod_fastcgi",
"mod_rewrite",
"mod_redirect",
"mod_setenv", ## before mod_status
"mod_status",
# ...
)
Alternatively you could use PHP to output the cors header
<?php
header("Access-Control-Allow-Origin: *");
?>
I also want to add that if you are sending http basic/digest auth data you cannot use wildcards for the origin. You have to use the actual source domain
setenv.add-response-header = ( "Access-Control-Allow-Origin" => "example.com" )
setenv.add-response-header = ( "Access-Control-Allow-Credentials" => "true" )
Because you are doing a cross domain POST, Angular is making a pre-flight OPTIONS request to check the Access Origin headers before making the POST.
The NET tab in your browser will confirm this.
Your server isn't responding well to the OPTIONS request and therefore Angular refuses to make the POST.
If you POST to your server with POSTMAN is everything OK?
I believe it is possible to configure Angular to not make the pre-flight request.
Alternatively, configure your server to respond correctly to OPTIONS requests, in particular returning the correct Access Origin headers in response to the OPTIONS request. (OPTIONS is just trying to find out if your server has these headers set, if it hasn't then why bother making the POST?)
Hopefully this information will point you in the right direction.
* can not be used in the case of credentials.
Server is disregarding your
setenv.add-response-header statement.
See the answer here:
CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true
Related
I am trying to call a PHP API running on localhost:8000 from a React app running on localhost:3000. After many tries I am still getting "CORS Preflight Did Not Succeed" error.
Sent from the React app:
Sent from the devtools:
My API has following headers:
if (#$_SERVER['HTTP_ORIGIN']) {
header("Origin: http://localhost:8000");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
}
I call the API with fetch like this (but it somehow sends empty request body):
let inputData:object = {email, password}
fetch("http://localhost:8000/data/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(inputData)
})
.then(response => {
console.log(response)
})
.catch(error => {
console.log(error)
})
The strange thing is that the requests are working normally when sent directly from the browser devtools (2nd screenshot) or API clients like Insomnia:
Problem
Your first screenshot indicates that the response to the preflight request has status code 404. However, a necessary condition for CORS preflight to succeed is an ok status (i.e. a status in the range 2xx). See the relevant section (3.2.3) of the Fetch standard:
A successful HTTP response, i.e., one where the server developer intends to share it, to a CORS request can use any status, as long as it includes the headers stated above with values matching up with the request.
A successful HTTP response to a CORS-preflight request is similar, except it is restricted to an ok status, e.g., 200 or 204.
(my emphasis)
Solution
Make sure your server responds with a 2xx status to preflight requests that are meant to succeed.
Additional remarks
Allowing the Origin header is never necessary, simply because it's set by the user agent. You can drop Origin from the value of the Access-Control-Allow-Headers response header.
Why you're setting an Origin header in the response is unclear... Origin is a request header. You should be able to drop that header("Origin: http://localhost:8000"); line.
Instead of "manually" implementing CORS (which is error-prone), you should consider using a proven CORS middleware.
Your cors origin must be localhost:3000.
header("Origin: http://localhost:3000");
Because your frontend running on 3000.
Where the request comes from should be added as cors definition.
Make sure you are not outputting anything in php before returning the response to the frontend application. A simple echo "test"; or a print_r, vardump etc. can trigger this error.
Also, make sure there are no empty lines before the opening <?php tags since they send a premature response to the frontend that may cause this error.
I'm trying to send some HTTP requests from my angular.js application to my server, but I need to solve some CORS errors.
The HTTP request is made using the following code:
functions.test = function(foo, bar) {
return $http({
method: 'POST',
url: api_endpoint + 'test',
headers: {
'foo': 'value',
'content-type': 'application/json'
},
data: {
bar:'value'
}
});
};
The first try ended up with some CORS errors. So I've added the following lines to my PHP script:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type, Origin, Authorization, Accept, Client-Security-Token, Accept-Encoding, X-Auth-Token, content-type');
The first error is now eliminated.
Now the Chrome's developer console shows me the following errors:
angular.js:12011 OPTIONS http://localhost:8000/test (anonymous
function)
423ef03a:1 XMLHttpRequest cannot load
http://localhost:8000/test. Response for preflight has invalid HTTP
status code 400
and the network request looks like I expected (HTTP status 400 is also expected):
I can't imagine how to solve the thing (and how to understand) why the request will send on localhost as OPTIONS and to remote servers as POST. Is there a solution how to fix this strange issue?
TL;DR answer
Explanation
The OPTIONS request is so called pre-flight request, which is part of Cross-origin resource sharing (CORS). Browsers use it to check if a request is allowed from a particular domain as follows:
The browser wants to send a request to a particular URL, let's say a POST request with the application/json content type
First, it sends the pre-flight OPTIONS request to the same URL
What follows depends on the pre-flight request's response HTTP status code:
If the server replies with a non-2XX status response, the browser won't send the actual request (because he knows now that it would be refused anyway)
If the server replies with a HTTP 200 OK (or any other 2XX) response, the browser will send the actual request, POST in your case
Solution
So, in your case, the proper header is present, you just have to make sure the pre-flight request's response HTTP status code is 200 OK or some other successful one (2XX).
Detailed Explanation
Simple requests
Browsers are not sending the pre-flight requests in some cases, those are so-called simple requests and are used in the following conditions:
One of the allowed methods:
- GET
- HEAD
- POST
Apart from the headers automatically set by the user agent (for example, Connection, User-Agent, etc.), the only headers which are allowed to be manually set are the following:
Accept
Accept-Language
Content-Language
Content-Type (but note the additional requirements below)
DPR
Downlink
Save-Data
Viewport-Width
Width
The only allowed values for the Content-Type header are:
application/x-www-form-urlencoded
multipart/form-data
text/plain
No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.
No ReadableStream object is used in the request.
Such requests are sent directly and the server simply successfully processes the request or replies with an error in case it didn't match the CORS rules. In any case, the response will contain the CORS headers Access-Control-Allow-*.
Pre-flighted requests
Browsers are sending the pre-flight requests if the actual request doesn't meet the simple request conditions, the most usually:
custom content types like application/xml or application/json, etc., are used
the request method is other than GET, HEAD or POST
the POST method is of an another content type than application/x-www-form-urlencoded, multipart/form-data or text/plain
You need to make sure that the response to the pre-flight request has the following attributes:
successful HTTP status code, i.e. 200 OK
header Access-Control-Allow-Origin: * (a wildcard * allows a request from any domain, you can use any specific domain to restrict the access here of course)
From the other side, the server may refuse the CORS request simply by sending a response to the pre-flight request with the following attributes:
non-success HTTP code (i.e. other than 2XX)
success HTTP code (e.g. 200 OK), but without any CORS header (i.e. Access-Control-Allow-*)
See the documentation on Mozilla Developer Network or for example HTML5Rocks' CORS tutorial for details.
I ran into a very similar problem writing an Angular 2 app - that uses a NODE server for the API.
Since I am developing on my local machine, I kept getting Cross Origin Header problems, when I would try to POST to the API from my Angular app.
Setting the Headers (in the node server) as below worked for GET requests, but my PUT requests kept posting empty objects to the database.
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE, PUT');
header('Access-Control-Allow-Headers: X-Requested-With, Content-Type,
Origin, Authorization, Accept, Client-Security-Token, Accept-
Encoding, X-Auth-Token, content-type');
After reading Dawid Ferenczy's post, I realized that the PREFLIGHT request was sending blank data to my server, and that's why my DB entries were empty, so I added this line in the NODE JS server:
if (req.method == "OPTIONS")
{
res.writeHead(200, {"Content-Type": "application/json"});
res.end();
}
So now my server ignores the PREFLIGHT request, (and returns status 200, to let the browser know everything is groovy...) and that way, the real request can go through and I get real data posted to my DB!
Just put
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
header("HTTP/1.1 200 ");
exit;}
at the beginning of your serverside app and you should be fine.
For spring boot application, to enable cors request, use #CrossOrigin(origins = "*", maxAge = 3600) on your respective controller.
Refer this doc
The best is to :
have proxy.conf.json set:
{
"/api": {
"target": "http://localhost:8080",
"secure": false,
"logLevel": "debug",
"changeOrigin": true
}
}
And then to make sure that URL that you are using in angular to send a request is relative (/api/something) and not absolute (localhost:8080/api/something). Because in that case the proxy won't work.
From Chrome v79+, OPTIONS Check(pre-flight request) will no longer appear in the network tab-Source
I'm trying to send a request from an Angular 8 app to Laravel 5.8 Passport API, but without success. I mean, with only a limited success. When I set withCredientials into the Angular request to true, the Preflight headers are trying to see whether the API would return proper headers, including Access-Control-Allow-Credentials: true, but the response shows that there's no such header, even though I'm setting it into the backend.
If I don't set withCredentials, the response headers include Access-Control-Allow-Credentials: true, just as expected, but I need that response in the preflight response as well.
I have tried enveloping the preflight request case in separate block, using
if (!$_SERVER['REQUEST_METHOD']=='OPTIONS')
and setting that header response explicitly, but without success as well.
A side note is that requesting that same URL from Postman works as expected (ever since Postman doesn't mess with CORS).
The request is being fired from the following code snippet:
await this.http.post(this.logInEndPoint, credentials, {
headers: this.httpHeaders,
withCredentials: true
}).subscribe(async res => {
...
The CORS middleware looks as follows:
$res->headers->set('Content-Type', 'application/json');
$res->headers->set('Access-Control-Allow-Origin', 'http://127.0.0.1:4200');
$res->headers->set('Access-Control-Allow-Credentials', 'true');
$res->headers->set('Access-Control-Max-Age', '60');
$res->headers->set('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token');
$res->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
if (!$_SERVER['REQUEST_METHOD']=='OPTIONS') {
$next($res);
} else {
return $res;
}
And that's where I define the use of the CORS middleware
api.php
Route::middleware('web', 'json.response', 'cors')->group(function() {
Route::post('login', 'AuthController#login');
...
I expect "Successfully logged in" message, but instead got Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/login' from origin 'http://127.0.0.1:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. in the Developer Tools.
After several days of struggling with that problem, I finally figured it out.
If I have to summarize the majority of problems, related to Angular consuming Laravel APIs, I'd point out the header settings in the backend. For me it was somewhere within the custom CORS middleware.
If I have to be honest, I'm not sure what's exactly wrong in the configuration above (I guess it is in the Allow-Methods header), but I'd share how I fixed my issue.
First of all, I removed all the custom middlewares I made. I started using the Barry vd. Heuvel's CORS one, adding it for the API's group only. There, I changed the default configuration. I set allowOrigins to my Angular server URI and allowedMethods to the requests I'm expecting to use. After publishing the CORS configuration file, I made sure to run my Angular app on 127.0.0.1 (and not on localhost). The same I did for the Laravel server.
After running both the apps on one and the same IP address and using the new CORS middleware, everything ran smoothly and without problems.
For an Angular 5 app, I have an auth service that does a HTTP POST which returns the session cookie (CORS) as shown below in the code below:
signIn(signInRequest: SignInRequest): Observable<SignInResponse> {
let headers: Headers = new Headers();
headers.append('Content-Type','application/json');
return this.http
.post("/login", {email: signInRequest._email,password:signInRequest._password}, { headers: headers, withCredentials: true })
.map(this.extractData)
.catch(this.handleErrorObservable);}
The response of the header contains the set-cookie as shown below:
and the request header is the following:
I know that the browser should be setting the cookie response. Why is it not doing it?
Your frontend is hosted on localhost:4200 and your backend is hosted on api.safra.me. By default, your browser won't send the cookies along the request unless you use the withCredentials in the login request as you already did, and all of the subsequent requests.
I've got a very strange issue.
local hosted PHP Slim App using XAMPP (localhost:4040)
local hosted Angular 4 App using CLI (localhost:4200)
Making API Requests using "Postman" and browser is no problem, everything works fine.
Now I'm integrating the requests into my Angular app using import { Headers, Http } from '#angular/http'; and observables.
const requestUrl = 'http://localhost:4040/register';
const headers = new Headers({
'content-type': 'application/x-www-form-urlencoded'
});
this.http
.get(requestUrl, {headers: headers})
.map(response => response.json())
.subscribe(result => {
console.log(result);
}, error => {
console.log(error);
});
The request always fails with:
Failed to load http://localhost:4040/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://localhost:4200' is therefore not allowed access.
But: I am definitely sending these headers!
public static function createJsonResponseWithHeaders($response, $requestedData)
{
// Add origin header
$response = $response->withHeader('Access-Control-Allow-Origin', '*');
$response = $response->withHeader('Access-Control-Allow-Methods', 'GET');
// Add json response and gzip compression header to response and compress content
$response = $response->withHeader('Content-type', 'application/json; charset=utf-8');
$response = $response->withHeader('Content-Encoding', 'gzip');
$requestedData = json_encode($requestedData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
$response->getBody()->write(gzencode($requestedData), 9);
if (!$requestedData || (count($requestedData) === 0)) {
return $response->withStatus(404)->write('Requested data not found or empty! ErrorCode: 011017');
}
return $response;
}
What I already tried for solving:
Run Slim App inside a Docker Container to get a different origin than localhost - same behaviour
Add allow-origin-header right on top of the index.php
header('Access-Control-Allow-Origin: *'); - same behaviour
Your requests are blocked because of CORS not being set up properly. There are other questions that address this, e.g. How to make CORS enabled requests in Angular 2
What you should ideally look at using is a proxy that forwards your requests to the API, the latest Angular CLI comes with support for a dev proxy (see https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md) out of the box. You set it up with a proxy.conf.json that could look like this:
{
"/api": {
"target": "http://localhost:4040",
"secure": false,
"pathRewrite": {"^/api" : ""}
}
}
What this piece of code does is any requests from Angular to a URI matching /api will be forwarded to localhost:4040.
Note that you will also need to figure out how your app will talk to the API server in a non-dev environment. I have been happy with using Nginx to serve Angular files, and act as proxy for the API.
Sorry, my bad. The solution is simple:
The "Cache-control" header in the request seems to be not allowed, although it worked fine when testing the api with Postman.
I removed the header from the request and everything worked well.