axios删除方法给出了403

时间:2018-08-14 08:20:40

标签: javascript node.js axios csrf interceptor

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

  

在Postman上运行正常,但在调用此API时给了我403   来自代码。

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

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 Security APP):

  

由于未找到您的会话,因此无法验证提供的CSRF令牌

我认为这已经由axios处理。

在调用delete方法时如何在标头中传递此值?

有帮助吗?

2 个答案:

答案 0 :(得分:1)

您可以:

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);
});
  

XMLHttpRequest.withCredentials属性是一个布尔值,   指示是否应进行跨站点访问控制请求   使用Cookie,授权标头或TLS等凭证进行   客户证书。设置withCredentials不会影响   同一站点的请求。

2-设置CSRF标头

要么:

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

答案 1 :(得分:0)

因此,经过多次尝试,我发现它可以正常工作。

请按照订单顺序,这很重要,否则将无法正常工作

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