我在ReactJS中编程时使用Axios,我假装向服务器发送DELETE请求。

要做到这一点,我需要头文件:

headers: {
  'Authorization': ...
}

而身体是由

var payload = {
    "username": ..
}

我一直在网上搜索,只发现DELETE方法需要一个“参数”,不接受“数据”。

我一直想这样发送

axios.delete(URL, payload, header);

甚至

axios.delete(URL, {params: payload}, header);

但似乎什么都不管用……

有人能告诉我,如果这是可能的(我假设是)发送一个删除请求与头部和主体,以及如何这样做?


当前回答

下面是使用axios发送各种http动词所需的格式的简要总结:

GET: Two ways First method axios.get('/user?ID=12345') .then(function (response) { // Do something }) Second method axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { // Do something }) The two above are equivalent. Observe the params keyword in the second method. POST and PATCH axios.post('any-url', payload).then( // payload is the body of the request // Do something ) axios.patch('any-url', payload).then( // payload is the body of the request // Do something ) DELETE axios.delete('url', { data: payload }).then( // Observe the data keyword this time. Very important // payload is the request body // Do something )

关键要点

获取请求可选地需要一个params键来正确设置查询参数 删除带有主体的请求需要将其设置在数据键下

其他回答

与axios无关,但可能帮助人们解决他们正在寻找的问题。PHP在执行delete调用时不解析post数据。Axios delete可以发送带有请求的主体内容。 例子:

//post example
let url = 'http://local.test/test/test.php';
let formData = new FormData();
formData.append('asdf', 'asdf');
formData.append('test', 'test');

axios({
    url: url,
    method: 'post',
    data: formData,
}).then(function (response) {
    console.log(response);
})

result: $_POST Array
(
    [asdf] => asdf
    [test] => test
)


// delete example
axios({
    url: url,
    method: 'delete',
    data: formData,
}).then(function (response) {
    console.log(response);
})

result: $_POST Array
(        
)

要在PHP中获得删除调用的post数据,请使用:

file_get_contents('php://input'); 

我也遇到过同样的问题…… 我通过创建一个自定义axios实例解决了这个问题。并使用它来进行身份验证删除请求..

const token = localStorage.getItem('token');
const request = axios.create({
        headers: {
            Authorization: token
        }
    });

await request.delete('<your route>, { data: { <your data> }});

如果我们有:

myData = { field1: val1, field2: val2 }

我们可以将数据(JSON)转换为字符串,然后将其作为参数发送到后端:

axios.delete("http://localhost:[YOUR PORT]/api/delete/" + JSON.stringify(myData), 
     { headers: { 'authorization': localStorage.getItem('token') } }
 )

在服务器端,我们得到我们的对象:

app.delete("/api/delete/:dataFromFrontEnd", requireAuth, (req, res) => {
    // we could get our object back:
    const myData = JSON.parse(req.params.dataFromFrontEnd)
 })

注意:2月14日15:49“x4wiz”的答案比我的回答更准确!我的解决方案是没有“身体”(在某些情况下可能会有帮助……)

更新:我的解决方案是不工作时,对象的重量为540字节(15*UUIDv4)和更多(请检查文档的确切值)。“x4wiz”(以及上面的许多其他解决方案)的解决方案要好得多。那么,为什么不删除我的答案呢?因为,它是有效的,但最重要的是,它给我带来了我的Stackoverflow的大部分声誉;-)

axios.post('/myentity/839', {
  _method: 'DELETE'
})
.then( response => {
  //handle success
})
.catch( error => {
   //handle failure
});

感谢: https://www.mikehealy.com.au/deleting-with-axios-and-laravel/

使用{data: {key: value}} JSON对象,示例代码片段如下所示:

// Frontend Code

axios.delete(`URL`, {
        data: {id: "abcd", info: "abcd"},
      })
      .then(res => {
        console.log(res);
      });

// Backend Code (express.js)

  app.delete("URL", (req, res) => {
  const id = req.body.id;
  const info = req.body.info;
  db.query("DELETE FROM abc_table WHERE id=? AND info=?;", [id, info],
    (err, result) => {
      if (err) console.log(err);
      else res.send(result);
    }
  );
});