javascript 错误:React JS 中的请求失败,状态码为 401 axios
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/53495922/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Error: Request failed with status code 401 axios in React JS
提问by test team
I am creating a login page using Laravel API and ReactJS front end. I am using Axiosin ReactJS to parse the username(email)and password. The API for login is http://127.0.0.1:8000/api/loginwhich works correctly in postman form-data. But when I entered the emailand the passwordin react front-end the echos is Error: Request failed with status code 401.This error throws by the catch function of axios. I am also using querystringnpm also. So which throws this error?
我正在使用 Laravel API 和 ReactJS 前端创建登录页面。我在 ReactJS 中使用Axios来解析username(email)和password。登录 APIhttp://127.0.0.1:8000/api/login在 postman 中正常工作form-data。但是当我进入email和password反应前端时,回声是Error: Request failed with status code 401.axios 的 catch 函数抛出的这个错误。我也在使用查询字符串npm。那么哪个会抛出这个错误?
My React JS code
我的 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;
The following is the Laravel API login code which requires the emailand password
以下是 Laravel API 登录代码,需要email和password
Laravel login API code
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);
}
}
}
Update
更新
As Alexsays hereI changed console.log("The error is : " + error);
as console.log("The error is : " + error.response);in catchfunction. It echos The error is : [object Object].
正如亚历克斯说,在这里我改变console.log("The error is : " + error);
为console.log("The error is : " + error.response);以catch功能。它回响The error is : [object Object]。
回答by Asif vora
You can post axios data by using FormData()like :
您可以使用FormData()发布 axios 数据,例如:
And then add the fields to the form you want to send :
然后将字段添加到您要发送的表单中:
let bodyFormData = new FormData();
bodyFormData.set('email',this.state.email);
bodyFormData.set('password', this.state.password);
And then you can use axios post method (You can amend it accordingly)
然后你可以使用 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);
});
回答by Rahul Jat
This is correct and working code solution
这是正确且有效的代码解决方案
The correct way to set headers in Axios
Axios中设置headers的正确方法
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))
cheers********
干杯********

