我正在撥打 xios 電話以獲取博客文章,但是我遇到了 CORS 問題,我嘗試了所有方法,但我不明白這個問題。
axios({
method: "POST",
url: process.env.REACT_APP_API_URL '/pages/articles',
headers: { 'Content-Type': 'application/json;charset=UTF-8', "Access-Control-Allow-Origin": "*", "Accept": "application/json" },
data: {
country: localStorage.getItem("locale")
}
}).then(result => {
setPosts(result.data.json.articles);
});
在我的 /config/bootstrap.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization');
header("Access-Control-Allow-Credentials: true");
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
if ($method == "OPTIONS") {
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method,Access-Control-Request-Headers, Authorization");
header("HTTP/1.1 200 OK");
die();
}
控制臺中的問題是:
Access to XMLHttpRequest at 'https://api.mysite.fr/pages/articles' from
origin 'https://mysite.fr' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have
HTTP ok status.
uj5u.com熱心網友回復:
請在服務器上應用 CORS 驗證,它需要是服務器端而不是前端,例如:JavaScript 中的請求 這將向您展示如何在 JavaScript 中發出此策略允許的請求。
var http_request;
http_request = new XMLHTTPRequest();
http_request.onreadystatechange = function () { /* .. */ };
http_request.open("POST", "process.env.REACT_APP_API_URL '/pages/articles'");
http_request.withCredentials = true;
http_request.setRequestHeader("Content-Type", "application/json");
http_request.send({ 'request': "authentication token" });
我們正在發送一個包含 JSON 的 POST 請求,并且我們將包含我們的 cookie。它產生一個帶有這些標頭的請求:
Origin: https://mysite.fr
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type
對于 PHP 專案
// Allow from any origin
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-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");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/496437.html
標籤:javascript 反应 科尔斯
上一篇:反應表單受控組件
下一篇:無法使用地圖回圈資料
