【问题标题】:Why won't my axios request return the proper data?为什么我的 axios 请求不会返回正确的数据?
【发布时间】:2021-05-31 10:53:22
【问题描述】:

我在我的 axios 实例中使用的 url 上运行了一个 api。如果提供了有效凭据,则为登录定义了一个路由,该路由返回 JWT 访问和刷新令牌。我可以使用邮递员对其进行测试,并且一切正常,但是在我使用 axios 的应用程序中,即使使用有效凭据,也不会返回任何令牌或错误。该 API 也为 cors 设置并且正在实时运行。

这里是 axios 实例:

import axios from 'axios';

const url = NOT SHOWN;

const axiosInstance = axios.create({
  baseURL: url,
  headers: {
    'Content-Type': 'application/json',
  },
});

export default axiosInstance;

这是基本的登录组件:

import React, { Component } from 'react';
import { Link as RouteLink, Redirect } from 'react-router-dom';
import axiosInstance from '../../axiosInstance';

//material ui
import Button from '@material-ui/core/Button';
import CssBaseline from '@material-ui/core/CssBaseline';
import TextField from '@material-ui/core/TextField';
import FormControlLabel from '@material-ui/core/FormControlLabel';
import Checkbox from '@material-ui/core/Checkbox';
import Link from '@material-ui/core/Link';
import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';
import { makeStyles } from '@material-ui/core/styles';
import Container from '@material-ui/core/Container';

class Login extends Component {
  state = {
    email: '',
    password: '',
    isAuthenticated: false,
  };

  login(email, password) {
    const data = {
      email: email,
      password: password,
    };
    axiosInstance
      .post('/login', data)
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  onSubmit = (e) => {
    const { email, password } = this.state;
    this.login(email, password);
  };

  onChange = (e) => this.setState({ [e.target.name]: e.target.value.trim() });

  render() {
    if (this.state.isAuthenticated) {
      return <Redirect to='/' />;
    }
    return (
      <Container component='main' maxWidth='xs' style={{ marginTop: '75px' }}>
        <CssBaseline />
        <div>
          <Typography component='h1' variant='h3' align='center'>
            Login
          </Typography>
          <form noValidate>
            <TextField
              variant='outlined'
              margin='normal'
              required
              fullWidth
              id='email'
              label='Email Address'
              name='email'
              autoComplete='email'
              autoFocus
              onChange={this.onChange}
            />
            <TextField
              variant='outlined'
              margin='normal'
              required
              fullWidth
              name='password'
              label='Password'
              type='password'
              id='password'
              autoComplete='current-password'
              onChange={this.onChange}
            />
            <FormControlLabel
              control={<Checkbox value='remember' color='primary' />}
              label='Remember me'
            />
            <Button
              type='submit'
              fullWidth
              variant='contained'
              color='primary'
              //className={classes.submit}
              onClick={this.onSubmit}
            >
              LOGIN
            </Button>
            <Grid container>
              <Grid item xs>
                <Link variant='body2'>Forgot password?</Link>
              </Grid>
              <Grid item>
                <Link component={RouteLink} to={'/signup'} variant='body2'>
                  {"Don't have an account? Sign Up"}
                </Link>
              </Grid>
            </Grid>
          </form>
        </div>
      </Container>
    );
  }
}

export default Login;

'''

【问题讨论】:

  • 您在浏览器的开发工具中看到请求了吗?如果你能看到它,它是否有正确的有效载荷(emailpassword)?响应是什么样的(在开发工具 Network -> Response 选项卡中)?
  • 因为你的登录功能使用了类的状态。您需要使用此关键字绑定登录功能。 this.login = this.login.bind(this) 在你的构造函数中
  • @Phil 在浏览器开发工具中请求似乎永远不会到达服务器,并且我在发布请求时收到 NS_BINDING_ABORTED 错误
  • 为遇到此问题的任何人解决了这个问题。在我的登录路径(服务器端)中,我在正文中寻找“电子邮件”和“密码”,但在客户端,我在登录函数中创建的数据对象内发送电子邮件和密码。
  • @stinny 你的评论毫无意义。您正在发布带有 emailpassword 属性的 JSON 请求正文。您的服务器端代码到底想做什么?错误在哪里?你做了什么来修复它?

标签: javascript reactjs axios


【解决方案1】:

我认为登录函数没有正确定义,所以它没有被调用。请尝试使用函数表达式:

login = (email, password) => {
    const data = {
      email: email,
      password: password,
    };
    axiosInstance
      .post('/login', data)
      .then((res) => {
        console.log(res.data);
      })
      .catch((err) => {
        console.log(err);
      });
  }

  onSubmit = (e) => {
    const { email, password } = this.state;
    login(email, password);
  };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2011-02-24
    • 1970-01-01
    • 1970-01-01
    • 2011-10-24
    • 1970-01-01
    相关资源
    最近更新 更多