React Native无CSRF令牌的Fetch请求失败

4

我一直在为使用Rails构建的Web应用程序开发移动端补充。使用Fetch API时,我一直收到“无法验证CSRF令牌真实性”的通知。

export const login = (user) => {
  fetch('http://localhost:3000/api/session', {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({user})
  })
  // promise handling
}

编辑:我已经成功解决了问题,但我仍然不太明白为什么。如果有人遇到同样的问题,这是我的解决方法。我从我的Rails应用程序中获取了form_authenticity_token,并将其保存为变量,然后传递给函数。我还没有测试删除凭据密钥。

export const login = (user, token) => {
  return fetch('http://localhost:3000/api/session', {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ user, authenticity_token: token })
  })

你在会话控制器中是否需要进行任何更改才能使其正常工作?我遇到了类似的问题,但是这个修复方法对我不起作用。 - JSilv
2个回答

1
你需要在头部添加CSRF令牌或在跨域请求中禁用/删除CSRF
export const login = (user) => {
  fetch('http://localhost:3000/api/session', {
    method: 'POST',
    credentials: 'include',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'X-CSRF-TOKEN': token
    },
    body: JSON.stringify({user})
  })
  // promise handling
}

1
谢谢您的回答,但不幸的是并没有解决问题。 - Peter Michael McKinley Salces
你从哪里获取令牌? - Vadym
这里有另一个脚本,你可以跟随使用React Native从Django应用程序检索csrf令牌 - Pir Shukarullah Shah

0

在使用Django后端时,您应该设置:

'X-CSRFToken': csrf_token  // not 'X-CSRF-Token' !!!

在您的JS请求头中。

环境: 要在后端设置令牌,请使用:

{% csrf_token %}  <!-- put this in your html template -->

然后,在JS代码中获取令牌:

const csrf_token = document.getElementsByName('csrfmiddlewaretoken')[0].value;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接