Sim*_*mon 5 csrf reactjs react-native react-relay
我正忙于开发一个 React Native 应用程序,该应用程序与 Django 服务器上的 GraphQL api 进行通信。
在 React Native 中,我使用 React Relay 尝试处理我的 GraphQL 请求(按照此处找到的指南),但我的请求遇到 403 问题。
回复说CSRF token missing or incorrect,我正在努力找出使其发挥作用的最佳方法。
我知道我需要首先获取 CSRF cookie 令牌,然后以某种方式将其与我的 GraphQL Post 请求一起传递,但运气不佳。我目前的实现如下......
fetch('http://' + ip + ':8000/sign-in/')
.then((response) => {
const cookieHeader = response.headers.map["set-cookie"]; // This gets me a cookie response with a CSRF token
fetch('http://' + ip + ':8000/graphql', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Cookie': cookieHeader, // Try and pass the received cookie to my POST
'XSRF-TOKEN': cookieHeader // Trying this as well
},
body: JSON.stringify({
query: operation.text,
variables,
}),
}).then(response => {
console.log('RESPONSE', response) // Currently getting a 403
return response.json()
})
})
Run Code Online (Sandbox Code Playgroud)
但这仍然给我带来 403 错误。
我似乎找不到更多关于如何解决这个问题的信息。谁能告诉我哪里出了问题,或者关于如何解决这个问题的一些建议?
(下面是我的 API 请求的快照)
所以设法让它与以下一起工作......
return getCsrfToken().then(csrfToken => {
if (csrfToken == null) {
console.log('CSRF NOT SET')
}
const url = 'http://' + ip + '/graphql'
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify({
query: operation.text,
variables,
}),
})
.then(response => {
return response.json()
})
.catch(error => {
console.log('POST ERROR', error)
})
});
function getCsrfToken() {
var url = 'http://' + ip + '/graphql';
return CookieManager.get(url).then(response => {
return response.csrftoken;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1524 次 |
| 最近记录: |