预检 CORS 错误,随后出现 404 错误

发布于 2025-01-10 02:35:50 字数 3277 浏览 1 评论 0原文

我在尝试从 React 应用程序的 API 获取数据时遇到问题。 我正在尝试使用 htaccess 文件来保护我的 API,因此当尝试在 Axios get 请求中发送身份验证时,我收到 CORS 错误和 404 错误。

这是我的 axios GET 请求:

getData = async () => {
    const username = "xyxyx";
    const pass = "xyxy";
    const basicAuth = "Basic " + Buffer.from(username +":"+pass).toString('base64');
    console.log("BasicAuth::", basicAuth);
    try {
    const {data} = await axios.get(UrlApi.Url, {
      //  mode: "no-cors" ,
      // headers : { 
        // 'Authorization':  basicAuth,
      // } 
      //  mode: "no-cors", 
      // allowCredentials: true,
      auth:  {
          username: "xyxyx",
          password: "xyxy"
        }
    });

如您所见,我评论了几行,因为我尝试了多种方法使其工作但没有成功。

下面是我的 API 的 index.php(不是我写的)

<?php
require "./database.php";
require "./datas.php";

header("Access-Control-Allow-Origin: http://southparagliding.ro");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
// header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");


$parsedUrl =  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/';
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$uri = explode( '/', $uri );

// endpoints starting with `/data` for GET, POST, DELETE posts
// everything else results in a 404 Not Found
if ($uri[1] !== 'data') {
  if($uri[1] !== 'datas'){
    header("HTTP/1.1 404 Not Found");
    exit();
  }
  print_r($uri[1]);
}

// endpoints starting with `/datas` for GET by type results in a 404 Not Found
// the post id is, of course, optional and must be a number; same with type
$dataId = null;
$type = null;

if ($uri[1] == 'datas' and isset($uri[2])) {
    $type = (string) $uri[2];
}

if ($uri[1] == 'data' and isset($uri[2])) {
    $dataId = (int) $uri[2];
}

$requestMethod = $_SERVER["REQUEST_METHOD"];

$dbConnection = (new Database())->connect();
// pass the request method and post ID to the Post and process the HTTP request:
$controller = new Data($dbConnection, $requestMethod, $dataId, $type, $parsedUrl);
$controller->processRequest();

另外,请参阅 de API 主文件夹内的 htaccess 文件。

#rewrite works: sp.ro/index.php/data => sp.ro/data 

RewriteEngine on
RewriteCond %{QUERY_STRING} ^$
# RewriteRule ^data$ /index.php/data [L,NE]
RewriteRule ^(.*)$ /index.php/data [L,NE]

RewriteEngine On


<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin http://localhost:3000
    # southparagliding.ro
    Header set Access-Control-Allow-Credentials true
    Header set Access-Control-Allow-Methods OPTIONS GET POST PUT DELETE
    </IfModule>

# RewriteEngine On
# RewriteCond %{REQUEST_METHOD} OPTIONS
# RewriteRule ^(.*)$ $1 [R=200,L]


#######this somehow works: basic auth for all methods but OPTIONS
# <If "%{REQUEST_METHOD} !=  'OPTIONS'">
# # Authentication directives...
# AuthUserFile "/home3/r94573sout/api/.htpasswd"
# AuthName "LockedApiII"
# AuthType Basic
# Require valid-user
# </If> 

我不明白我哪里错了。 我在这方面花了很多时间,所以如果您有任何想法,我将非常感激。

谢谢你!

I am experiencing an issue when trying to get data from API for my react app.
I am trying to pass protect my API using htaccess file so when trying to send auth in Axios get request I receive a CORS error and 404 error.

This is my axios GET request:

getData = async () => {
    const username = "xyxyx";
    const pass = "xyxy";
    const basicAuth = "Basic " + Buffer.from(username +":"+pass).toString('base64');
    console.log("BasicAuth::", basicAuth);
    try {
    const {data} = await axios.get(UrlApi.Url, {
      //  mode: "no-cors" ,
      // headers : { 
        // 'Authorization':  basicAuth,
      // } 
      //  mode: "no-cors", 
      // allowCredentials: true,
      auth:  {
          username: "xyxyx",
          password: "xyxy"
        }
    });

As you can see I have several lines commented as I tried in so many ways to make it work but without success.

Below is the index.php of my API (which I didn't write)

<?php
require "./database.php";
require "./datas.php";

header("Access-Control-Allow-Origin: http://southparagliding.ro");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: OPTIONS,GET,POST,PUT,DELETE");
header("Access-Control-Max-Age: 3600");
// header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With");


$parsedUrl =  $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].':'.$_SERVER['SERVER_PORT'].'/';
$uri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

$uri = explode( '/', $uri );

// endpoints starting with `/data` for GET, POST, DELETE posts
// everything else results in a 404 Not Found
if ($uri[1] !== 'data') {
  if($uri[1] !== 'datas'){
    header("HTTP/1.1 404 Not Found");
    exit();
  }
  print_r($uri[1]);
}

// endpoints starting with `/datas` for GET by type results in a 404 Not Found
// the post id is, of course, optional and must be a number; same with type
$dataId = null;
$type = null;

if ($uri[1] == 'datas' and isset($uri[2])) {
    $type = (string) $uri[2];
}

if ($uri[1] == 'data' and isset($uri[2])) {
    $dataId = (int) $uri[2];
}

$requestMethod = $_SERVER["REQUEST_METHOD"];

$dbConnection = (new Database())->connect();
// pass the request method and post ID to the Post and process the HTTP request:
$controller = new Data($dbConnection, $requestMethod, $dataId, $type, $parsedUrl);
$controller->processRequest();

Also, see my htaccess file that is inside the de API main folder.

#rewrite works: sp.ro/index.php/data => sp.ro/data 

RewriteEngine on
RewriteCond %{QUERY_STRING} ^$
# RewriteRule ^data$ /index.php/data [L,NE]
RewriteRule ^(.*)$ /index.php/data [L,NE]

RewriteEngine On


<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin http://localhost:3000
    # southparagliding.ro
    Header set Access-Control-Allow-Credentials true
    Header set Access-Control-Allow-Methods OPTIONS GET POST PUT DELETE
    </IfModule>

# RewriteEngine On
# RewriteCond %{REQUEST_METHOD} OPTIONS
# RewriteRule ^(.*)$ $1 [R=200,L]


#######this somehow works: basic auth for all methods but OPTIONS
# <If "%{REQUEST_METHOD} !=  'OPTIONS'">
# # Authentication directives...
# AuthUserFile "/home3/r94573sout/api/.htpasswd"
# AuthName "LockedApiII"
# AuthType Basic
# Require valid-user
# </If> 

I don't understand where I am going wrong.
I have spent a lot of time on this so if you have any idea I will much appreciate it.

Thank you!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

无妨# 2025-01-17 02:35:50

您调用的 API 不会将 Authorization 视为 CORS 允许的标头:

Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With

因此您无法从不同来源发出包含授权的请求,

auth: {
  username: "xyxyx",
  password: "xyxy"
}

因为这会导致 授权标头。这一限制只能由编写 API 的人解除。它必须是:

Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization

The API which you call does not consider Authorization a CORS-allowed header:

Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With

Therefore you cannot make requests from a different origin that include authorization like

auth: {
  username: "xyxyx",
  password: "xyxy"
}

because this leads to an Authorization header. This restriction can only be lifted by the one who wrote the API. It must be:

Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, X-Requested-With, Authorization
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文