-1

I am trying to experiment with Redux Toolkit Query mutations.

What I have now at the front-end:

import { createApi, fetchBaseQuery } from "@reduxjs/toolkit/query/react";

export const postApi = createApi({
  reducerPath: "postApi",
  baseQuery: fetchBaseQuery({
    baseUrl: "https://webcodingcenter.com/shared/",
    prepareHeaders: (headers, { getState }) => {
      headers.set("Content-Type", "application/json");
      return headers;
    }
  }),
  endpoints: (builder) => ({
    getPost: builder.query({
      query: (id) => `get_post.php?id=${id}` // expects a JSON response
    }),
    updatePost: builder.mutation({    // <-- attention here
      query: (body) => {
        console.log(123, body);
        return {
          url: `update_post.php`,
          method: "POST",
          body
        };
      }
    })
  })
});

// Export hooks for usage in functional components, which are
// auto-generated based on the defined endpoints
export const { useGetPostQuery, useUpdatePostMutation } = postApi;

And the back end (update_post.php):

<?php
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: HEAD, GET, POST, PUT, PATCH, DELETE, OPTIONS");
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('Content-Type: application/json');
if ($_SERVER['REQUEST_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();
}
$str="HELLO WORLD";
$r="";
for ($i = 0; $i < strlen($str); $i++){
   if (rand(0,100)>50) $r .= strtoupper($str[$i]);
   else                $r .= strtolower($str[$i]);
}
file_put_contents("data".$_POST["id"].".txt",$r);
echo json_encode($_POST);
//echo json_encode(array("post"=>$r));
?>

As you can see from the Code Sandbox here, $_POST is always empty. How can I pass the data to $_POST?

Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100

1 Answers1

0

This solves it:

$data = json_decode(file_get_contents('php://input'), true);
Chong Lip Phang
  • 8,755
  • 5
  • 65
  • 100