我需要一个登录函数来返回一个令牌,但它总是返回 undefined。
src/api/login.js
That is my function
import axios from 'axios';
const linkApi = 'http://localhost/api';
const logIn = async (email, password) => {
const params = new URLSearchParams()
params.append('email', email)
params.append('password', password)
params.append('action', 'LOGIN')
const config = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
await axios.post(linkApi, params, config)
.then(response => {
if(response.data.error === false) {
return response.data.token;
} else {
throw new Error(response.data.message)
};
})
}
export default logIn;
我使用这个屏幕上的功能:
src/views/Login/index.js
import React, { Fragment } from "react";
import { Button, Text } from "react-native";
import { useNavigation } from '@react-navigation/native';
import Container from "../../components/Container";
import Logo from "../../components/Logo";
import StyledInput from "../../components/StyledInput";
import ButtonView from "../../components/ButtonView";
import logIn from "../../api/login";
const screen = () => {
// const navigation = useNavigation();
const [email, setEmail] = React.useState("");
const [password, setPassword] = React.useState("");
const [errorMessage, setErrorMessage] = React.useState("");
const sendRequest = async () => {
try {
const token = await logIn(email, password)
console.warn(token)
} catch (erro) {
setErrorMessage(erro.message)
}
}
return (
<Fragment>
<Container>
<Logo />
<Text style={{ color:"#fff" }}>{errorMessage}</Text>
<StyledInput
placeholder="Usuario"
onChangeText={string => setEmail(string)}
value={email}
keyboardType="email-address"
autoCompleteType="email"
placeholder="Digite seu email"
placeholderTextColor = "#CCC"
/>
<StyledInput
placeholder="Senha"
secureTextEntry={true}
onChangeText={string => setPassword(string)}
value={password}
autoCompleteType="password"
placeholder="Digite sua senha"
placeholderTextColor = "#CCC"
/>
</Container>
<ButtonView>
<Button
title="Entrar"
onPress={sendRequest}
color="#fe9f29"
/>
</ButtonView>
</Fragment>
);
};
export default screen;
但是屏幕上的const token总是返回undefined
当我在登录函数中执行 console.warn(response.data.token)
时,控制台会正常显示令牌。
拜托,有人可以帮我吗?
答案 0 :(得分:0)
您需要返回 axios.post(...
链的结果。现在,该承诺的已解析值正在被丢弃。