Axios Intercerptors Headers - javascript

I have a very "strange" error.
I'm adding an interceptor in my axios and adding a new "header", below an example..
axiosInstance.interceptors.request.use(function (config) {
config.headers['X-Panel-Host'] = document.location.hostname;
return config;
});
After I added this new header, I started having the "CORS ERROR" problem, and so far I wasn't having it, however, I added mine in the backend (PHP) with the authorization as below.
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
header("Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, X-Panel-Host, X-Host");
However, I still get a return in the CORS api, if I remove the line that contains "X-PANEL-HOST" the api works again, what did I forget to do?

Related

CORS/JavaScript/Laravel: Sending request to Digital Ocean server and receiving data (Headers issues)

So, what I'm trying to do is use a Digital Ocean droplet as an api for an application hosted on a different server. Currently, I'm just developing so this server is from my localhost:3000.
On my client side code (JavaScript) I have:
handleSendData = () => {
const request = new XMLHttpRequest()
request.open('POST', 'http://my-droplet-ip/api/create-image')
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
request.setRequestHeader('Access-Control-Allow-Origin', 'http://my-droplet-ip')
request.send(JSON.stringify(data-object))
}
Finally, in my Laravel application (Laravel Framework 5.8.18) I have a route under routes/api.php:
Route::post('/create-image', 'CreateData');
And I have a controller CreateData.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class CreateImage extends Controller
{
/**
* Handle the incoming request.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function __invoke(Request $request)
{
return response('Hello World', 200)
->header('Content-Type', 'application/json; charset=UTF-8')
->header('Access-Control-Allow-Origin', '*');
}
}
The problem is when I try to run this request, I get a CORS error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://my-droplet-ip/api/create-image. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)
Under the networking tab I get a 404 not found and the Access header is not there in the response.
Any thoughts out there on this issue?
There is a simple solution to this and it is ok for testing on you local machine.
You could just put in index file to allow cors, but I suggest you building middleware for this.
Here is a link it is explained really nice:)
https://medium.com/#petehouston/allow-cors-in-laravel-2b574c51d0c1
You can put also this in index.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
Hope it helps :D

HTTP 405 error while trying to DELETE from web service

I have a simple Java web service that handles my SQL method with Jersey. The HTTP call is from an Angular project. GET and POST are working fine, but when I try a DELETE, I get an HTTP 405 error.
This is how I call the method in Angular:
deletaDados(id){
this.service.deleteData(id)
}
+
deleteData(id){
return this.http.delete(`${this.api}/${id}`).subscribe((res) => {
});;
}
And this is the DELETE Java method:
#DELETE
#Path("{id}/")
public Response delete(#PathParam("id") long id) throws SQLException, ClassNotFoundException{
ofertaDAO dao = new ofertaDAO();
dao.delete(id);
return Response
.status(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Credentials", "true")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.entity(id)
.build();
}
Seem right... No idea why I'm getting the 405 error.
If the DELETE coming from your frontend JavaScript code is a cross-origin request, then your browser (automatically on its own) will send a CORS preflight OPTIONS request first.
So it seems like the 405 you’re seeing may be the response to that preflight OPTIONS request — and if so, then you’ll need to have an explicit OPTIONS handler in your server-side Java code.
That OPTIONS handler should just send back a response with a 200 status and the necessary CORS headers, with no response body; so, something like this:
#OPTIONS
public Response options(){
return Response
.status(200)
.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Headers", "origin, content-type, accept, authorization")
.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD")
.header("Access-Control-Max-Age", "1209600")
.build();
}
Incidentally, also note that for the Access-Control-Max-Age response header there’s probably not much point in setting a value that’s any greater than 600 (10 minutes) — because if you do set a value greater than that for it, Chrome will just clamp it to 600 anyway.
And as far as why you don’t also run into that 405 when you send a GET or POST from your frontend JavaScript code, the reason is that the GET and POST requests your code is sending don’t have characteristics (such as custom headers) that’ll trigger your browser to do a preflight. But cross-origin DELETE requests always trigger browsers to do a preflight.

Posting data to different domain using PHP, AJAX don't work

I'd like to post data from domain1.com to domain2.com using AJAX, but my request fails.
Here's is my code on domain1.com:
$.ajax({
type: 'POST',
url: 'https://domain2.com/payment/api/server',
crossDomain: true,
data: {
Name: $("#name").val().trim(),
Email: $("#email").val().trim()
},
dataType: 'json',
success: function(data) {
alert('Success');
},
error: function (data) {
alert('POST failed.');
}
});
and here's my server side code on domain2.com:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://domain1.com/api/': case 'http://domain1.com/api/':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
$name = $_POST['Name'];
echo $name; // Just to check if I receive the value from index.php
You are checking if Origin HTTP header equals to 'http://domain1.com/api/'. However, MDN CORS docs say:
The origin is a URI indicating the server from which the request initiated. It does not include any path information, but only the server name.
You have to remove the path from the string, i.e. it has to be 'http://domain1.com'.
Corrected server.php code:
switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://domain1.com':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
break;
}
$name = $_POST['Name'];
echo $name;
As a side note: if you are using the "HTTP_ORIGIN" header to "secure" your requests, you should rethink it. Anyone can spoof this header and arbitrarily set the value. You are better off using some kind of key/secret to avoid unwanted requests. See: Is CORS a secure way to do cross-domain AJAX requests?

CORS is not working with ionic

I am trying to send a json to a php script on a server and even though I have included header in php script to have CORS the console throws error
error message
XMLHttpRequest cannot load http://www.awesomegag.0fees.us/updata.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 403.
my code :
php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Content-Type: application/json; charset=UTF-8");
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_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']))
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"hello";
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
?>
My app.js
.controller('datactr', ['$scope','$http','ApiEndpoint',function($scope,$http,ApiEndpoint) {
$scope.submit=function(){
console.log("step1");
$http({
method:'POST',
url:'http://www.awesomegag.0fees.us/updata.php',
data:{
'name':$scope.name
}
}).success(function(data,status,header,config){
console.log("step2");
console.log(data);
})
});
I tried to make it work using proxy method by making path /api and proxyUrl to updata.php address in ionic.project and then replace url in http service to /api. I get a 500 internal server error.
Can anyone help ?
Update: I have moved to a different server where everything works fine.I guess it is some problem with the server but have no idea how to fix it.
Looks like that your server doesn't allow OPTIONS method.
Modern browser do "pre-flight" request for cross origin request to make sure that it is allowed to do so before sending GET/POST request.
Solution: Enable OPTIONS command. Example for Apache http://httpd.apache.org/docs/trunk/mod/mod_allowmethods.html

Cross-Origin Request Blocked Angular JS Put request

I'm developing a REST-ful application using Yii framework for the server side and Angular JS for the client side
I'm using the restfulyii extension to generate the api
:And I'm facing a problem when I'm sending a PUT request.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ..... This can be fixed by moving the resource to the same domain or enabling CORS.
But it's working for post + get requests
I saw different solutions but none of them worked.
I tried to put those is server side
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");
header("Access-Control-Max-Age: 1000");
and tried to put this code in the angular js module:
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
and also I tried to put
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
The request converted into OPTIONS request
and the response from the server became as following:
Access-Control-Allow-Headers:x-requested-with, Content-Type, origin, authorization, accept, client-security-token
Access-Control-Allow-Methods:GET, POST, PUT, DELETE, OPTIONS Access-Control-Allow-
Origin:http://localhost:8383
Access-Control-Max-Age:1000
Connection:close
Content-Type:text/html Date:Fri, 24 Oct 2014 06:49:32 GMT
Server:Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.9 X-Powered-By:PHP/5.5.9
I have a base controller for all my rest controllers that use restangular which has the following events.
public function restEvents()
{
$this->onRest('req.cors.access.control.allow.origin', function() {
return ['*']; //List of sites allowed to make CORS requests
});
$this->onRest('req.cors.access.control.allow.methods', function() {
return ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS']; //List of allowed http methods (verbs)
});
$this->onRest('req.auth.cors', function ($allowed_origins) {
if (in_array('*', $allowed_origins)) {
return true;
}
if((isset($_SERVER['HTTP_ORIGIN'])) && (( array_search($_SERVER['HTTP_ORIGIN'], $allowed_origins)) !== false )) {
return true;
}
return false;
});
$this->onRest('req.cors.access.control.allow.headers', function($application_id) {
return ["X_{$application_id}_CORS", "Content-Type", "Authorization", "X_REST_REQUEST"];
});
}
Client side I am using restangular with the following options:
RestangularProvider.setDefaultHttpFields({withCredentials: true});
RestangularProvider.setDefaultHeaders({X_REST_CORS: 'Yes'});
RestangularProvider.setDefaultHttpFields({cache: false});
I hope this helps....

Categories