错误:React JS中的请求失败,状态代码为401 axios

vbkedwbf  于 2023-10-18  发布在  iOS
关注(0)|答案(4)|浏览(185)

我正在使用Laravel API和ReactJS前端创建登录页面。我在ReactJS中使用Axios来解析username(email)password。登录的API是http://127.0.0.1:8000/api/login,它在postman form-data中可以正常工作。但是当我在react前端输入emailpassword时,echos是Error: Request failed with status code 401.这个错误由axios的catch函数抛出。我也在使用querystring npm。那么,是什么抛出了这个错误呢?

我的React JS代码

import React, { Component } from 'react';
import { Button, Card, CardBody, CardGroup, Col, Container, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
import axios from 'axios';
import  { Redirect } from 'react-router-dom'
import querystring from 'querystring';

class Login extends Component
{
  constructor(props)
  {
    super(props);
    this.onClick = this.onClick.bind(this);

    this.state = {
      email:"",
      password:""
    }
  }

  onClick(event)
  {
    var self = this;
    var payload={
      "email":this.state.email,
      "password":this.state.password,
    }
    //axios.post('http://127.0.0.1:8000/api/login', payload) .then((response) => {}
    console.log("1. Hello before axios.post");
    //axios.post('http://127.0.0.1:8000/api/login', payload)
    axios.post('http://127.0.0.1:8000/api/login', querystring.stringify({payload}))

    .then((response) =>
    {
      console.log("2. Inside axios response");
      console.log(response);
      if(response.data.code == 200)
      {
        //Set localstorage:
        const userDetails = {userName: this.state.email}
        localStorage.setItem('userDetails', JSON.stringify(userDetails));

        console.log("Login successfull");
        return <Redirect to='/Master'  />

      }

      else if(response.data.code == 204)
      {
        console.log("Username password do not match");
        alert(response.data.success)
      }

      else if(response.data.code == 401)
      {
        alert(response.data.success)
      }

      else
      {
        console.log("Username does not exists");
        alert("Username does not exist");
      }
    })

    .catch(function (error)
    {
      console.log("The error is : " + error);
    });
}
  render()
  {
    return (
      <div className="app flex-row align-items-center">
        <Container>
          <Row className="justify-content-center">
            <Col md="8">
              <CardGroup>
                <Card className="p-4">
                  <CardBody>
                    <h1>Login</h1>
                    <p className="text-muted">Sign In to your account</p>
                    <InputGroup className="mb-3">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="icon-user" />
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input type="text" placeholder="Username" />
                    </InputGroup>
                    <InputGroup className="mb-4">
                      <InputGroupAddon addonType="prepend">
                        <InputGroupText>
                          <i className="icon-lock" />
                        </InputGroupText>
                      </InputGroupAddon>
                      <Input type="password" placeholder="Password" />
                    </InputGroup>
                    <Row>
                      <Col xs="6">
                        <Button color="primary" className="px-4" onClick={this.onClick}>
                          Login
                        </Button>
                      </Col>
                      <Col xs="6" className="text-right">
                        <Button color="link" className="px-0">
                          Forgot password?
                        </Button>
                      </Col>
                    </Row>
                  </CardBody>
                </Card>
                <Card
                  className="text-white bg-primary py-5 d-md-down-none"
                  style={{ width: 44 + "%" }}
                >
                  <CardBody className="text-center">
                    <div>
                      <h2>Sign up</h2>
                      <p>
                        Are you a new user to the Restaurant system? Hooray now , you can create an account...
                      </p>
                      <Button color="primary" className="mt-3" active>
                        Register Now!
                      </Button>
                    </div>
                  </CardBody>
                </Card>
              </CardGroup>
            </Col>
          </Row>
        </Container>
      </div>
    );
  }
}

export default Login;

以下是Laravel API登录代码,需要emailpassword

Laravel登录API代码

<?php
namespace App\Http\Controllers\API;
use Illuminate\Http\Request; 
use App\Http\Controllers\Controller; 
use App\User; 
use Illuminate\Support\Facades\Auth; 
use Validator;
class UserController extends Controller 
{
    public $successStatus = 200;

    public function login()
    { 
        if(Auth::attempt(['email' => request('email'), 'password' => request('password')]))
        {
            $user = Auth::user(); 
            $success['token'] =  $user->createToken('MyApp')-> accessToken; 
            return response()->json(['success' => $success], $this-> successStatus);
        } 

        else
        { 
            return response()->json(['error'=>'Unauthorized'], 401); 
        } 
    }
}

更新

正如Alex所说,我在catch函数中将console.log("The error is : " + error);改为console.log("The error is : " + error.response);。它回应The error is : [object Object]

cgfeq70w

cgfeq70w1#

这是正确的和工作的代码解决方案

  • 在Axios中设置标题的正确方法 *
axios.post('http://10.0.1.14:8001/api/logout',request_data, {
          headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer '+token
          },      
      })      
      .then((response) => {
        console.log('response',response.data)

      })
      .catch((error) => {
        alert('error',error.response)
        dispatch(userUpdateProfileFail())

      })

  // console.log('----cheers---------',data)
dispatch(userUpdateProfileSuccess(data))

干杯干杯

tp5buhyn

tp5buhyn2#

您可以使用FormData()发布axios数据,如:
然后将字段添加到要发送的表单中:

let bodyFormData = new FormData();
bodyFormData.set('email',this.state.email);
bodyFormData.set('password', this.state.password);

然后你可以使用axios post方法(你可以相应地修改它)

axios({
    method: 'post',
    url: 'http://127.0.0.1:8000/api/login',
    data: bodyFormData,
    config: { headers: {'Content-Type': 'multipart/form-data' }}
    })
    .then(function (response) {
        //handle success
        console.log(response);
    })
    .catch(function (response) {
        //handle error
        console.log(response);
    });
xyhw6mcr

xyhw6mcr3#

我的问题是无效的Token,所以检查令牌,authorizationunauthenticated

noj0wjuj

noj0wjuj4#

我在应用程序中使用GitHub API时遇到了同样的问题。我的API访问令牌已过期,因此API没有发送任何结果,这就是为什么我的应用程序中没有任何内容可供删除。我从GitHub的设置中创建了一个新令牌,并在发送请求时使用它。问题已解决。

相关问题