Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  151] [ 2]  / answers: 1 / hits: 29068  / 7 Years ago, fri, april 14, 2017, 12:00:00

Is there a way to send an object to an API using axios?



This the code I use:



axios.get('/api/phones/create/', {
parameters: {
phone: this.phone
}
})
.then(response => {
console.log(response.data)
})
.catch(function (error) {
console.log(error)
})


on the php side, I have the following:



public function create($phone)
{
return $phone;
}


I get the following error:



GET http://crm2.dev/api/phones/create 500 (Internal Server Error)
dispatchXhrRequest @ app.6007af59798a7b58ff81.js:256
xhrAdapter @ app.6007af59798a7b58ff81.js:93
dispatchRequest @ app.6007af59798a7b58ff81.js:662
app.6007af59798a7b58ff81.js:2266 Error: Request failed with status code 500
at createError (app.6007af59798a7b58ff81.js:600)
at settle (app.6007af59798a7b58ff81.js:742)
at XMLHttpRequest.handleLoad (app.6007af59798a7b58ff81.js:158)


If I try, axios.get('/api/phones/create/hello') I get hello in the console log.



Is there a way to do this?


More From » axios

 Answers
1

It depends on what you mean by send an object.



Since you're using a GET request and passing the object in the parameters, you can serialize it into query params as part of the GET request. This wouldn't really send the object but rather use it to build the query section of the URL for the GET request.



For example, here's how you can make a request to /api/phones/create?phone=123:



axios.get('/api/phones/create/', {
params: {
phone: '123'
}
})


If you want to actually send the object as a serialized JSON to your API, you can use a POST or a PUT request, depending on the semantics of your API.



For example, to send { phone: 123 } to your api, you could do:



axios.post('/api/phones/create/', {
phone: '123'
});


Note: axios expects the key params for parameters.


[#58148] Wednesday, April 12, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dequant

Total Points: 88
Total Questions: 99
Total Answers: 95

Location: Ukraine
Member since Sun, Dec 13, 2020
4 Years ago
dequant questions
;