React无法显示未授权登录的401响应.statusText的通知,这也是未定义的警告?

问题描述 投票:1回答:2

我试图故意显示一个通知,显示用户凭证不正确或未经授权。然而,没有任何显示

下面是React组件。

import React, {Component} from 'react';
import ReactDom from "react-dom";
import '../css/app.scss';
import 'bootstrap';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';

export class Login extends Component {
    constructor(props){
        super(props);
        this.state={
            email:'',
            password:'',
            username:'',
            errorMsg:'',
            hasError: false
        }
    }

    handleClick() {
        fetch('/login', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'credentials': "same-origin"
            },
            body: JSON.stringify({
                'email' : this.state.email,
                'password' : this.state.password,
                'username' : this.state.username
            })
        })
        .then(function(response) {
            if (!response.ok) {
                if (response.status === 401) {
                    console.log(response.statusText);
                    this.setState({'hasError': true});
                    this.setState({'errorMsg': response.statusText})
                }
            }
        })
        .catch(error => console.log(error) );
    }

    render() {
        const hasError = this.state.hasError;
        let hasErrorDiv;

        if (hasError) {
            hasErrorDiv = <div id="mAlert" className="alert alert-danger">{this.state.errorMsg}</div>;
        } else {
            hasErrorDiv = <div id="mAlert" ></div>;
        };
        return (
            <div className="container">
                <div>
                    {hasErrorDiv}
                    <TextField
                        type="text"
                        hinttext="Enter your username"
                        floatinglabeltext="username"
                        onChange = {(event) => this.setState({username:event.currentTarget.value})}
                    />
                    <br/>
                    <TextField
                        type="email"
                        hinttext="Enter your email"
                        floatinglabeltext="email"
                        onChange = {(event) => this.setState({email:event.currentTarget.value})}
                    />
                    <br/>
                    <TextField
                        type="password"
                        hinttext="Enter your Password"
                        floatinglabeltext="Password"
                        onChange = {(event) => this.setState({password:event.currentTarget.value})}
                    />
                    <br/>
                    <Button label="Login" onClick={() => this.handleClick()}>
                        Login
                    </Button>
                </div>
            </div>
        );
    }
}

ReactDom.render(<Login />, document.getElementById('Login'));

正如你可以看到下面的截图,

the server returns invalid credentials

我想把错误显示给最终用户。

此外,在控制台是一些奇怪的东西,因为我想,401响应不被认为是一个错误,所以是什么捕捉错误,这是显示在控制台,指?

先谢谢你

reactjs fetch http-status-code-401
2个回答
1
投票

好吧,我不得不创建自己的通知流程来处理401错误。

首先,并不是所有的通知都能在React 16.13.2下工作。

第二,"this is undefined "的错误信息来自于catch内部,不明白 "this "到底是什么。

第三,我不得不使用async类型,然后使用waiting--用于等待fetch POST返回的响应。

第四,我不得不使用.json来读取错误,这是JSON格式的 - {'error':'Invalid credentials'}。- 截屏

以下是我的代码。

import React, {Component} from 'react';
import ReactDom from "react-dom";
import '../css/app.scss';
import 'bootstrap';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import $ from 'jquery';

export class Login extends Component {
    constructor(props){
        super(props);
        this.state={
            email:'',
            password:'',
            username:'',
            errorMsg:'',
            hasError: false
        };
        this.handleClick = this.handleClick.bind(this);
    }

    componentDidMount() {
        // console.log(React.version);
    }

    setNotifications(param) {
        // console.log('makes it to setNotification func');
        let notifications = $('#notificaitons');
        notifications.addClass("alert alert-danger");
        notifications.html(param.error);
    }

    async handleClick() {
        const requestOptions = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'credentials': "same-origin"
            },
            body: JSON.stringify({
                'email' : this.state.email,
                'password' : this.state.password,
                'username' : this.state.username
            })
        };
        const response = await fetch('/login', requestOptions);
        const data = await response.json();
        this.setState({ errorMsg: data.error });
        this.setNotifications(data);
    }

    render() {
        return (
            <div className="container">
                <div>
                    <div id="notificaitons"></div>
                    <TextField
                        type="text"
                        hinttext="Enter your username"
                        floatinglabeltext="username"
                        onChange = {(event) => this.setState({username:event.currentTarget.value})}
                    />
                    <br/>
                    <TextField
                        type="email"
                        hinttext="Enter your email"
                        floatinglabeltext="email"
                        onChange = {(event) => this.setState({email:event.currentTarget.value})}
                    />
                    <br/>
                    <TextField
                        type="password"
                        hinttext="Enter your Password"
                        floatinglabeltext="Password"
                        onChange = {(event) => this.setState({password:event.currentTarget.value})}
                    />
                    <br/>
                    <Button label="Login" onClick={() => this.handleClick()}>
                        Login
                    </Button>
                </div>
            </div>
        );
    }
}

ReactDom.render(<Login />, document.getElementById('Login'));

screen shot of the fetch 401 response

现在,我必须做更多的编码, 比如如何清除通知,可能是某种淡化, 可能必须做某种成功的通知, 以及警告版本,但至少它的工作。

另外,这只是一个div,我加了一个'alert警报-危险'的类,同时通过.html添加内容。如果要做一个成功的版本,我会添加一个 "alert alert-success "的类,以此类推。

© www.soinside.com 2019 - 2024. All rights reserved.