问题
I am trying to POST some data from Vue.js to a backend based on Symfony using the following code.
updateQuestion : function() {
axios.post('/staff/question/api/' + this.id,{
id : 'test',
name : 'sree'
})
.then( response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
},
However, the parameters that I am attaching to the POST request are not reaching my controller. So, I tried the alternate format for POST requests and still, the parameters are not reaching the controller. Please tell me what's wrong.
Alternate format:
updateQuestion : function() {
axios({
method : 'POST',
url : '/staff/question/api/' + this.id,
data: {
id : 'test',
name : 'sree'
}
})
.then( response => {
console.log(response);
})
.catch(error => {
console.log(error);
})
},
回答1:
I also encountered this problem! My post data was found in the controller:
$request->getContent();
My vue script
onSubmit() {
axios.post('/test/post/data', { test: "test" })
.then(response => {
console.log(response.data);
});
},
My Symfony controller:
public function postData(Request $request)
{
$data = $request->getContent();
$data = json_decode($data, true);
return $this->json($data);
}
回答2:
Install FOSRestBundle to solve this problem.
composer require friendsofsymfony/rest-bundle
https://github.com/FriendsOfSymfony/FOSRestBundle
Using this bundle, incoming json requests will be automatically translated into an array, directly available in $request->request->all() or $request->request->get('myparam').
Documentation excerpt:
This bundle provides various tools to rapidly develop RESTful API's & applications with Symfony. Features include:
- A View layer to enable output and format agnostic Controllers
- A custom route loader to generate url's following REST conventions
- Accept header format negotiation including handling for custom mime types
- RESTful decoding of HTTP request body and Accept headers
- Exception controller for sending appropriate HTTP status codes
回答3:
Its nothing wrong with your syntax. But check this.id - if you are not doing any mistake and this.id is undefined, or something. And if this.id is ok, then log complete request in controller and look for data.
updateQuestion: function () {
axios
.post('/staff/question/api/' + this.id, {
id: 'test',
name: 'sree'
})
.then(response => {
console.log(response)
})
.catch(error => {
console.error(error)
})
}
回答4:
Instead of using $request->getContent(); you can do the following in your JavaScript file to be able to use $request->request->all() in your backend.
I needed this for writing tests, since $request->getContent(); is empty in my tests.
const params = new URLSearchParams();
params.append('id', 123456);
params.append('name', 'some name');
axios({
method: 'post',
url: '/staff/question/api/' + this.id,
data: params
});
See also: https://github.com/axios/axios/issues/1195#issuecomment-347021460
来源:https://stackoverflow.com/questions/47056498/post-requests-with-axios-not-sending-parameters