我已经建立了一个使用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上复制它?我尝试在线搜索,但是找不到讨论的任何此类方法。
答案 0 :(得分:0)
您可以 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
}