Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  125] [ 7]  / answers: 1 / hits: 83494  / 8 Years ago, wed, january 4, 2017, 12:00:00

So I have this code:



axios({
method: 'post',
url,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: {
json,
type,
}
})


Originally I had the normal axios.post but I changed to this because I thought it might have been a header problem. However I am still detecting nothing in my $_REQUEST nor $_POST. However, it is receiving data in file_get_contents(php://input).



Any idea what is wrong?



Edit



Okay I think I know what's wrong. It's posting it as a json object so it can only be read in the php://input. How do I change it to a normal string in axios?


More From » php

 Answers
28

From the documentation (I haven't preserved links in the quoted material):



Using application/x-www-form-urlencoded format


By default, axios serializes JavaScript objects to JSON.



PHP doesn't support JSON as a data format for populating $_POST.


It only supports the machine-processable formats natively supported by HTML forms:



  • application/x-www-form-urlencoded

  • multipart/form-data



To send data in the application/x-www-form-urlencoded format instead, you can use
one of the following options.


Browser


In a browser, you can use the URLSearchParams API as follows:


var params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Note that URLSearchParams is not supported by all browsers, but there
is a polyfill available (make sure to polyfill the global
environment).


Alternatively, you can encode data using the qs library:


var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 }));


Or you could customise your PHP so it can handle JSON as per this answer on another question.


[#59467] Monday, January 2, 2017, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
myrap

Total Points: 407
Total Questions: 105
Total Answers: 109

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
myrap questions
Tue, Feb 8, 22, 00:00, 2 Years ago
Wed, Jan 15, 20, 00:00, 4 Years ago
Thu, Oct 24, 19, 00:00, 5 Years ago
Thu, Oct 3, 19, 00:00, 5 Years ago
Mon, Aug 12, 19, 00:00, 5 Years ago
;