【问题标题】:axios delete method gives 403axios删除方法给出403
【发布时间】:2019-01-21 00:59:23
【问题描述】:

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

它在 Postman 中运行良好,但在调用此 API 时给了我 403 来自代码。

下面是我的示例代码sn-p:

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 方法时如何在标头中传递此值?

有什么帮助吗?

【问题讨论】:

  • 你也可以分享服务器代码吗?
  • 实际上它正在由其他团队处理,因此暂时无法检查。我给定的代码似乎正确?我只是想确认其中没有任何奇怪的东西:)
  • 在你的拦截器中试试config.crossDomain: true。然后 axios 将首先发出预检选项请求。也许它有帮助......
  • @ThomasKleßen 我试过你说的。同样的错误!
  • @JayeshDhandha 是否有任何 cmets 或答案可以帮助您解决问题?您需要更多帮助吗?让我们知道

标签: javascript node.js axios csrf interceptor


【解决方案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

【讨论】:

    【解决方案2】:

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

    请按照顺序进行这很重要,否则将不起作用

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-01
      • 1970-01-01
      • 2021-10-05
      • 2016-10-29
      相关资源
      最近更新 更多