"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why is Axios POST Data not Accessible in $_POST?

Why is Axios POST Data not Accessible in $_POST?

Published on 2024-11-08
Browse:900

Why is Axios POST Data not Accessible in $_POST?

Axios Post Parameters Not Read by $_POST

You're posting data to a PHP endpoint using Axios and expecting to access it in $_POST or $_REQUEST. However, you're currently unable to detect it.

Originally, you used the default axios.post method, but switched to the code snippet provided due to a suspected header issue. Despite this change, the data remains undetectable.

Upon further investigation, you've realized that Axios is posting the data as a JSON object, which is accessible through file_get_contents("php://input"). Your goal is to send the data as a normal string instead.

Solution:

According to Axios's documentation, the default behavior is to serialize JavaScript objects to JSON for posting. However, PHP does not support JSON as a data format for populating $_POST. It only supports the formats natively supported by HTML forms:

  • application/x-www-form-urlencoded
  • multipart/form-data

To send data in the desired format, you have several options:

  • Using the URLSearchParams API (in a browser)
  • Using the qs library to encode data

Alternatively, you could customize your PHP configuration to handle JSON data as suggested in another related question.

Release Statement This article is reprinted at: 1729607537 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3