axios 删除方法给出 403

axios delete method gives 403

我正在从我的 node-js 应用程序中调用 delete 方法。

Its working fine from Postman but giving me 403 while calling this API from code.

下面是我的示例代码片段:

const instance = axios.create();
instance.interceptors.request.use((config) => {
    config.baseURL = 'https://test-dev.com/api/portfolio'
    config.headers = { 'Authorization' : 'Bearer ' + <TOKEN>}
    return config;
});
instance.delete('/admin?users=<VALUE>').then(function(response) {
    console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
    console.log("Deletion failed with error:" + error);
});

编辑:

响应(来自spring安全APP):

Could not verify the provided CSRF token because your session was not found

我以为这已经被 axios 处理了。

如何在调用 delete 方法时将此值传递给 headers?

有什么帮助吗?

您可以:

1 - 使用 withCredentials 属性:

withCredentials: true

所以:

axios.delete({
    url: 'https://test-dev.com/api/portfolio/admin?users=' + <VALUE>,
    headers: { 'Authorization' : 'Bearer ' + <TOKEN>},
    withCredentials: true
}).then(function(response) {
    console.log("Deleted: "+<VALUE>);
}).catch(function (error) {
    console.log("Deletion failed with error:" + error);
});

The XMLHttpRequest.withCredentials property is a Boolean that indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests.

2 - 设置 CSRF headers

或者:

headers: {'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-TOKEN' : document.querySelector('meta[name="csrf-token"]').getAttribute('content')}

headers: {'X-Requested-With': 'XMLHttpRequest',
         'X-CSRFToken': 'your token here'}

或者只是:

headers: {'X-Requested-With': 'XMLHttpRequest'}

3 - 禁用风险自负,如果可能

看看this article

所以经过多次尝试,我发现它有效。

请按顺序排列这很重要,否则将无法使用

axios.delete(
        URL,
        {headers: {
          Authorization: authorizationToken
        },
        data:{
          source:source
        }}
      );