Angularjs getting OPTIONS and POST request - php

I am sending a POST request to a different domain like so in angular:
$http.post('http://domain.com/auth', { email: $scope.email, password: $scope.password })
And in my request logs, it was only sending an OPTION request.
So I added this to my domain.com/auth:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
But now, I am getting an OPTION request first, and then a POST request. So because my OPTION request is first, I think it is still messing with my results.
Does anyone know how to only get the POST request and not the OPTIONS request?

You can prevent a preflight on POST by triggering a simple request
To achieve this, use $httpParamSerializerJQLike to encode your data (make sure to inject the serializer) and set the content-type to application/x-www-form-urlencoded:
$http({
url: 'YOUR_ENDPOINT',
method: 'POST',
data: $httpParamSerializerJQLike(YOUR_DATA),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})

Related

On a PUT fetch the CORS issue is triggered "has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header", headers setted WORDPRESS

Even though I set the headers in the file functions.php, the error keeps appearing, I tried with several different hooks:
function add_cors_http_header()
{
if (isset($_SERVER['HTTP_ORIGIN'])) {
// Decide if the origin in $_SERVER['HTTP_ORIGIN'] is one
// you want to allow, and if so:
// header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
// may also be using PUT, PATCH, HEAD etc
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
}
add_action('init', 'add_cors_http_header');
add_action('send_headers', 'add_cors_http_header');
add_action('rest_pre_serve_request', 'add_cors_http_header');
(Not all add_action at the same time)
And I also tried without the isset and in the header.php
EDIT ---
As requested, the client that is running is Vanilla Javascript, I made the same fetch on Postman and it worked, it's about joining a user to a guild in discord, hre is the code:
const args = JSON.stringify({
access_token: token,
});
const response = await fetch(
`https://discord.com/api/guilds/${this.guildID}/members/${userID}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
Authorization: `BOT ${this.bot_token}`,
},
body: args,
}
);
Access-Control-Allow-Origin (and similar headers) are for the server to define, and not the client. In this case, the server is the Discord API.
I'm guessing the confusion here is that your client is JavaScript, but you're trying to modify the headers in PHP. I think you should try to add the headers in JavaScript directly. Perhaps there's an Origin header you need?
I suggest looking at your Postman headers being sent and add them right in your JavaScript. For example:
headers: {
"Content-Type": "application/json",
Authorization: `BOT ${this.bot_token}`,
Origin: "http://localhost",
},
If that doesn't work, open your Chrome Dev Tools, open the Network tab, and look at the outgoing request, and see what headers it is sending and compare them with Postman. If Postman can work, just repeat what it is doing.
Regarding the WordPress function, I think you can remove it entirely as JavaScript is the client, not PHP/WordPress.

Classic cross domain ajax with jquery client side PHP server side

It is about a javascript pixel to follow up who does what in a sales funnel on the web.
I have a javascript script on my customer thrivecart domain (e.g. https://ownspace.thrivecart.com)
I want to make a request to another domain (e.g. https://emails.mycustomer.com) from which the javascript script is from.
Here is the main part of the javacsript code on https://ownspace.thrivecart.com :
$(document).ready(function () {
console.log("loading pixel");
$.ajax({
url: 'https://emails.mycustomer.com/server_side_script.php',
type: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'X-Requested-With': 'XMLHttpRequest'},
data: {my:ciphered_get_parameters},
success: function (result) {
console.log(result);
}
});
});
Here is what I have server side for the moment : (server_side_script.php)
<?php
header('Content-Type:application/json');
header("Access-Control-Allow-Origin:https://ownspace.thrivecart.com");
header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, Accept");
// Special data treatment
I get this error on the thrivecart page :
Failed to load https://emails.mycustomer.com/server_side_script.php: Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers in preflight response.
However, I read that "
Access-Control-Allow-Headers :
Indicates which headers are supported by the response’s url for the purposes of the CORS protocol."
As the header is on in the PHP code, I don't understand why it does not work.
I even tried to set the X-Requested-With header in the response with NGINX conf file, restarting the server.
But, I think I miss a point.
Appears to be a typo in
header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, Accept");
Try
header("Access-Control-Allow-Headers:Content-Type, Authorization, X-Requested-With, Accept");

CORS Allow-Access-Control-Origin on Mobile Chrome

I am getting an error on mobile, when I use Chrome to try out my new responsive web app. I have done everything from add php headers in several different ways, to passing headers in my ajax request. On the web, I used CORS toggle, a Chrome extension that allows you to toggle on and off CORS, which fixes the problem on web. Yet I cannot seem to find a solution like this for mobile. Anyway I can bypass CORS on mobile Chrome??
I have tried ALL of these ways, and nothing seems to work..
php option 1:
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With');
header('Access-Control-Allow-Methods: GET, PUT, POST');
?>
php option 2:
<?php
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true ");
header("Access-Control-Allow-Methods: OPTIONS, GET, POST");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
echo "You have CORS!";
?>
jQuery AJAX:
$.ajax({
url: '<MY API ENDPOINT>',
method: 'POST',
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With",
'Access-Control-Allow-Methods': "GET, PUT, POST",
'Authorization':
'Bearer <MY TOKEN>',
'Cache-Control': 'no-cache'
},
data: formData,
processData: false,
contentType: false
}).done(function(res) {
Remove the access control headers from your ajax request. Access control headers are automatically set by the browser as defined in the W3C CORS spec.
Whatever headers you include in your ajax request, you need to allow in the server response. In your case it's Authorization and Cache-Control. Add them to Access-Control-Allow-Headers.
Use option 2 of your php code. It includes a response for the cors preflight OPTIONS request. Option 1 will not work for that reason.

CORS work correctly on sharing host but not in localhost

I try to build a simple api base app with Laravel (as backend) and angularjs (as frontend).
In the beginning, I faced this error:
XMLHttpRequest cannot load http://127.0.0.1:8000/api/myroute. 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' is therefore not allowed access.
http://127.0.0.1:8000/api/myroute is my route to get some data, defined in Laravel as POST route.
That's while I've added the CORS middleware on my routes (according this sample) in this way:
Cors Middleware:
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token');
}
and the below code is my $http code that I send request in Angularjs:
$http({
method: 'POST',
url: 'http://127.0.0.1:8000/api/myroute',
headers: {
'Content-Type': 'application/json'
}
}).then(function (response) {
console.log(response);
}, function (reject) {
console.log(reject);
});
I should to add this point that when I upload my project on a host, this Cors works Ok!
My problem is just http://localhost.
I also tried this in Firefox but the result was same, just Firefox not shown the Cross Origin Error and it's the only difference.
In this time I could not develop my project on host and I need to work locally.
So I need help!
Try to add below codes as header to your laravel's index.php file:
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization');
but be careful about cross origion!

CORS AJAX request from a NodeJS server to a PHP server

So I'm making an AJAX request from a node server to a PHP server. The PHP server looks like this:
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
echo json_encode($data);
The request is being sent via AngularJS list this:
app.controller('MainController', function($scope, $http) {
var req = {
method: 'POST',
url: 'http://testsite.com/api/login',
headers: {
'Content-Type': 'application/json'
},
data: {
Data : {
email: 'test',
}
}
}
$http(req)
.success(function(response){ console.log(response); })
.error(function(){ console.log("error")});
});
This works perfectly. The problem starts when I run this within an NodeJS app, everything is exactly the same except that the NodeJS with ExpressJS is running node bin/www. The error I get is:
Failed to load resource: the server responded with a status of 405 (Method Not Allowed)
Failed to load resource: Request header field Content-Type is not allowed by Access-Control-Allow-Headers
XMLHttpRequest cannot load http://testsite.com/api/login. Request header field Content-Type is not allowed by Access-Control-Allow-Headers
Any idea on what I could be missing?
Try adding this header in PHP server response
Access-Control-Allow-Methods: GET, POST
The client needs to know which methods the server can handle as part of the pre-flight request

Categories