react-native - React Native 中的 Csrf 令牌发布
问题描述
我使用 Node 和 Express 作为框架制作了一个网站。现在我们正在转向 React Native 移动应用程序。在制作登录页面时,我提出了一个帖子请求,如下所示
index.js
import React, { Component } from 'react'
import {
View,
TextInput,
Text,
Button,
Alert,
} from 'react-native';
import styles from './styles'
class Home extends Component {
constructor(props){
super(props)
state = {email: "", password: ""}
}
checkLogin(){
const { email, password } = this.state;
if(email ==="admin" || password === "admin" || true){
fetch('http://localhost:3021/user/signin', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then((response) => {
console.log(response)
})
.catch((error) => {
console.error(error);
})
}
else{
Alert.alert('Error', 'Email/Password mismatch', [{
text: 'Okay',
}])
}
}
render(){
const {heading, input, parent} = styles
return (
<View style={parent}>
<Text style={heading}> Login into the Application </Text>
<TextInput style={input} placeholder="Email" onChangeText={text => this.setState({email: text})} underlineColorAndroid='black'/>
<TextInput style={input} secureTextEntry={true} placeholder="Password" onChangeText={text => this.setState({password: text})} underlineColorAndroid='black'/>
<Button title={"Login"} onPress = {() => this.checkLogin()} />
</View>
);
}
}
export default Home
当我发送此请求时,我没有收到任何响应,并在 Postman 上检查了响应,它以无效的 csrf 令牌和 403 错误的形式出现。最初在我的 Web 应用程序中登录时,表单包含一个 CSRF 令牌,其传递如下所示:
<input type = "hidden" name="_csrf" value="{{ csrfToken }}">
如何在 React Native App 上复制它?我尝试在网上搜索,但是找不到任何讨论的此类方法。
解决方案
您可以 1. 在请求标头中添加 CSRF 令牌或 2. 在后端禁用 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
}
推荐阅读
- php - 如何在 laravel 中使用纯 sql 函数 - php
- javascript - 在顶级文档/窗口上注册“全局监听器”与事件监听器
- c++ - Visual Studio LNK2001 错误,尽管在 C++ 中对 ffmpeg 库使用了 extern "C"
- mysql - 为什么 JSON OVERLAPS MYSQL 函数不起作用?
- typescript - 我可以在没有 strictNullChecks: false 的情况下解决这个问题吗?
- python - 对 python venv 和全局模块的不满
- python - lstm 中的最后一个密集层出错,期望 (1,) 但给定 (88,),但对于我的模型,我需要最后一层仅为 88
- bazel - 读取 WORKSPACE 中的文件内容
- excel - 如何忽略使用可选参数的代码?
- javascript - 快递+猫鼬。如何使用相同的“hidenId”参数获取所有备份集合?