Home > OS >  CORS block the request
CORS block the request

Time:01-25

i am using react as frontend and php as backend, frontend previously i was uploading on aws amplify and backend upload on lightsail, however due to amplify is https but lightsail is http api which wont let me pass the info so I changed to aws s3 as frontend, every function works fine but only update function will show error

Access to XMLHttpRequest at 'http://3.222.98.25/api/Update.php' from origin 'http://post-fetch-api.s3-website-ap-southeast-2.amazonaws.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

anyone knows reason? i put every CORS functions i can in the update file, is works on local enviorment, but not online enviorment

//this is php update page

<?php 
// if request is OPTIONS, disconnect
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
    header('Access-Control-Allow-Headers: token, Content-Type');
    header('Access-Control-Max-Age: 1728000');
    header('Content-Length: 0');
    header('Content-Type: text/plain');
    die();
}
 
 // Headers
  header('Access-Control-Allow-Origin: *');
  header('Content-Type: application/json');
 header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
  header('Access-Control-Allow-Headers: Access-Control-Allow-Headers,Content-Type,Access-Control-Allow-Methods, Authorization, X-Requested-With');

  include_once '../config/Database.php';
  include_once '../models/Post.php';

  // Instantiate DB & connect
  $database = new Database();
  $db = $database->connect();

  // Instantiate blog post object
  $post = new Post($db);

  // Get raw posted data
  $data = json_decode(file_get_contents("php://input"));

  // Set ID to update
  $post->id = $data->id;

  $post->title = $data->title;
  $post->body = $data->body;
  

  // Update post
  if($post->update()) {
    echo json_encode(
      array('message' => 'Post Updated')
    );
  } else {
    echo json_encode(
      array('message' => 'Post Not Updated')
    );
  }
// here is react update page

import { useState, useEffect } from "react";
import axios from "axios";
import { Link } from "react-router-dom";
import { useNavigate, useParams } from "react-router-dom";

export default function Update() {
  const [inputs, setInputs] = useState({});
  //const[post,setPost]=useState({});
  const navigate = useNavigate();
  const { id } = useParams();
  useEffect(() => {
    getSinglePost();
  }, []);

  function getSinglePost() {
    axios
      .get(`http://3.222.98.25/api/read_single.php?id=${id}`)
      .then((res) => {
        console.log(res.data);
        setInputs(res.data);
      })
      .catch((err) => console.log(err));
  }
  const handleChange = (e) => {
    const name = e.target.name;
    const value = e.target.value;
    setInputs((values) => ({ ...values, [name]: value }));
  };
  const handleSubmit = (e) => {
    e.preventDefault();
    axios
      .put("http://3.222.98.25/api/Update.php", inputs)
      .then((response) => {
        console.log(response.data);
        navigate("/read");
      })
      .catch((err) => console.log(err));
  };
  return (
    <div>
      <Link to="/">Show Posts</Link>
      <h1 style={{ marginTop: "150px" }}>Update a post</h1>
      <form onSubmit={handleSubmit}>
        <div className="marginBottom">
          <label className="marginRight">Title:</label>
          <input
            type="text"
            value={inputs.title}
            name="title"
            onChange={handleChange}
            required
          ></input>
        </div>
        <div className="marginBottom bodyCenter">
          <label className="marginRight">Body:</label>
          <textarea
            style={{ height: "50px" }}
            type="text"
            name="body"
            value={inputs.body}
            onChange={handleChange}
            required
          ></textarea>
        </div>
        <button>update</button>
      </form>
    </div>
  );
}

CodePudding user response:

A cross-origin request (CORS) is a type of request made by a web application that is running on one domain, to a resource on a different domain. This type of request is blocked by web browsers by default, as a security measure, to prevent cross-site scripting (XSS) attacks.

To enable cross-origin requests in PHP, you can add the appropriate headers to the server response. The headers you need to set depend on the type of request you are making.

For example, if you are making a simple request (GET, HEAD, or POST) from a web page to your PHP server, you need to set the following headers:

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, HEAD, POST");

The first line allows any domain to access the resource, while the second line specifies that the server will only accept GET, HEAD, and POST requests.

If you are making a preflight request (OPTIONS), you also need to set the following headers:

header("Access-Control-Allow-Headers: Content-Type");
header("Access-Control-Max-Age: 86400");

The first line specifies which headers are allowed in the actual request, and the second line specifies how long (in seconds) the preflight request will be cached by the browser.

Additionally, you can also set the Access-Control-Allow-Credentials header to allow credentials (cookies, etc) to be sent along with the request.

header("Access-Control-Allow-Credentials: true");

Please note that these headers should be set before any other output is sent from the server, and that these examples are for simple cases and may need to be adapted to fit your specific use case.

you will need to set the withCredentials property to true and set the Access-Control-Allow-Origin header on the server to allow the domain of your web page to access the resource.

Here is an example of how you might make a CORS GET request using the `XMLHttpRequest' object:

var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/resource", true);
xhr.withCredentials = true;
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4 && xhr.status === 200) {
    console.log(xhr.responseText);
  }
};
xhr.send();
  • Related