Welcome Guest, Not a member yet? Register   Sign In
CORS in method delete
#1

(This post was last modified: 10-08-2021, 01:43 PM by rafinhaa.)

Hello everyone, I have a study api running on localhost:80 has the following routes:

PHP Code:
$routes->group("api", ["namespace" => "App\Controllers\Api"] , function($routes){
 
$routes->group("users", function($routes){
 
  $routes->get(  "list",        "ApiController::listUsers");
 
  $routes->post(  "add",          "ApiController::addUser");
 
  $routes->get(  "single/(:num)","ApiController::singleUser/$1");
 
  $routes->put(  "update/(:num)","ApiController::updateUser/$1");
 
  $routes->delete("delete/(:num)","ApiController::deleteUser/$1");
 }); 
}); 

My frontend is in ReactJS and works on localhost:3000 I'm using axios to make requests, GET and POST are working normally.

PHP Code:
        axios.get('http://localhost/api/users/list'
 
      .then(response => setUsers(response.data.data));

 
async function createUser(userUsersInput) {
 var 
bodyFormData = new FormData();
 
bodyFormData.append('username',user.username);
 
bodyFormData.append('email',user.email);

 const 
response await axios.post('http://localhost/api/users/add'bodyFormData);
 
console.log(response);
 } 

When I try to use the DELETE method I get CORS error


In the browser console I have this axios error:
Code:
Access to XMLHttpRequest at 'http://localhost/api/users/delete/6' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

xhr.js:187 DELETE http://localhost/api/users/delete/6 net::ERR_FAILED

Uncaught (in promise) Error: Network Error
    at createError (createError.js:16)
    at XMLHttpRequest.handleError (xhr.js:99)

[Image: Screenshot-1.png]
[Image: Screenshot-2.png]
[Image: Screenshot-3.png]

apache config
Code:
<VirtualHost *:80>
  ServerAdmin webmaster@localhost
  DocumentRoot /var/www/html/public
  
  <Directory /var/www/html>
    Header set Access-Control-Allow-Origin *
    Header always set Access-Control-Allow-Methods "GET,POST,PUT,DELETE,HEAD,OPTIONS"
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

.htaccess
Code:
<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin *
    Header set Access-Control-Allow-Methods "GET,POST,PUT,DELETE,HEAD,OPTIONS"
    Header set Access-Control-Allow-Credentials true
</IfModule>

Thank you all
Reply
#2

You've got 404 response in your screenshot.
Reply
#3

First fix your 404 error.

This is what I use for CORS headers in .htaccess file.

Code:
## .htaccess Control For CORS Configuration

# Add Font Awesome Font Types
AddType application/vnd.ms-fontobject .eot
AddType application/x-font-ttf        .ttf
AddType application/x-font-opentype  .otf
AddType application/font-woff        .woff
AddType application/font-woff2        .woff2

<IfModule mod_headers.c>
        <FilesMatch "\.(ttf|ttc|otf|eot|woff|woff2|svg|svgz|jpg|png|ico|font.css|css|js)$">
            ## un-remark this one for all access and remark out the one below it
            #Header set Access-Control-Allow-Origin "*"
            ## Change this to your local host url. and https or http
            Header add Access-Control-Allow-Origin: "https://yoursite.com"
            Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
            Header add Access-Control-Allow-Headers: "Upgrade-Insecure-Requests"
        </FilesMatch>
</IfModule>


Try that.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4

Use this middlewear (filter)

<?php namespace Modules\Common\Filters;

use CodeIgniter\config\Services;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\Response;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;


class CorsFilter implements FilterInterface
{
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{


}

public function before(RequestInterface $request, $arguments = null)
{



if (array_key_exists('HTTP_ORIGIN', $_SERVER)) {
$origin = $_SERVER['HTTP_ORIGIN'];
} else if (array_key_exists('HTTP_REFERER', $_SERVER)) {
$origin = $_SERVER['HTTP_REFERER'];
} else {
$origin = $_SERVER['REMOTE_ADDR'];
}
$allowed_domains = array(
'http://localhost:4200',
'https://exmple.com',
'https://www.exmple.com',
);


if (in_array($origin, $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
}

header("Access-Control-Allow-Headers: Origin, X-API-KEY, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
header("Access-Control-Allow-Methods: GET, PUT, POST, DELETE, PATCH, OPTIONS");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 3600");
header('content-type: application/json; charset=utf-8');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header("HTTP/1.1 200 OK CORS");
die();
}

}


}
Enlightenment  Is  Freedom
Reply
#5

Thanks to everyone the paliz tip worked well for me!
But I had to disable auto routing of routes
[img][Image: Screenshot-1.jpg][/img]
Did any detail go unnoticed?
Reply
#6

your well come man
Enlightenment  Is  Freedom
Reply




Theme © iAndrew 2016 - Forum software by © MyBB