Why is Axios POST Data not Accessible in $_POST?

Mary-Kate Olsen
Release: 2024-10-23 01:03:03
Original
153 people have browsed it

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.

The above is the detailed content of Why is Axios POST Data not Accessible in $_POST?. For more information, please follow other related articles on the PHP Chinese website!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!