How can I send an object using axios?

War*_*rio 4 javascript axios

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)
    })
Run Code Online (Sandbox Code Playgroud)

on the php side, I have the following:

public function create($phone)
{
    return $phone;
}
Run Code Online (Sandbox Code Playgroud)

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)
Run Code Online (Sandbox Code Playgroud)

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

Is there a way to do this?

nem*_*035 6

这取决于您“发送对象”的意思。

由于您正在使用GET请求并在参数中传递对象,因此您可以将其序列化为GET请求中的查询参数。这实际上不会发送对象,而是使用它来为GET请求构建URL的查询部分。

例如,这是您可以向发出请求的方法/api/phones/create?phone=123

axios.get('/api/phones/create/', {
    params: {
        phone: '123'
    }
})
Run Code Online (Sandbox Code Playgroud)

如果要实际将对象作为序列化JSON发送到API,则可以使用POST或PUT请求,具体取决于API的语义。

例如,要发送{ "phone": "123" }到您的api,您可以执行以下操作:

axios.post('/api/phones/create/', {
  phone: '123'
});
Run Code Online (Sandbox Code Playgroud)

注意:axios需要params参数密钥。