Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/solr/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs React无法为未经授权的登录显示401 response.statusText通知,这也是未定义的警告吗?_Reactjs_Fetch_Http Status Code 401 - Fatal编程技术网

Reactjs React无法为未经授权的登录显示401 response.statusText通知,这也是未定义的警告吗?

Reactjs React无法为未经授权的登录显示401 response.statusText通知,这也是未定义的警告吗?,reactjs,fetch,http-status-code-401,Reactjs,Fetch,Http Status Code 401,我试图故意显示一个通知,表明用户凭据不正确或未经授权。但什么也没有表现出来 以下是反应组件: 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-

我试图故意显示一个通知,表明用户凭据不正确或未经授权。但什么也没有表现出来

以下是反应组件:

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'));
import React,{Component}来自'React';
从“react dom”导入react dom;
导入“../css/app.scss”;
导入“引导”;
从“@material ui/core/TextField”导入TextField;
从“@material ui/core/Button”导入按钮;
导出类登录扩展组件{
建造师(道具){
超级(道具);
这个州={
电子邮件:“”,
密码:“”,
用户名:“”,
errorMsg:“”,
hasError:错误
}
}
handleClick(){
获取(“/login”{
方法:“POST”,
标题:{
“接受”:“应用程序/json”,
“内容类型”:“应用程序/json”,
“凭证”:“同一来源”
},
正文:JSON.stringify({
“电子邮件”:this.state.email,
“密码”:this.state.password,
“用户名”:this.state.username
})
})
.然后(功能(响应){
如果(!response.ok){
如果(response.status==401){
console.log(response.statusText);
this.setState({'hasError':true});
this.setState({'errorMsg':response.statusText})
}
}
})
.catch(错误=>console.log(错误));
}
render(){
const hasError=this.state.hasError;
让哈斯罗迪夫;
if(hasrerror){
hasErrorDiv={this.state.errorMsg};
}否则{
hasErrorDiv=;
};
返回(
{haserrodiv}
this.setState({username:event.currentTarget.value})
/>

this.setState({email:event.currentTarget.value}) />
this.setState({password:event.currentTarget.value}) />
this.handleClick()}> 登录 ); } } ReactDom.render(,document.getElementById('Login'));
如以下屏幕截图所示:

我想向最终用户显示错误

另外,在控制台中有些奇怪,因为我认为401响应不被认为是错误,那么在控制台中显示的catch错误是指什么


提前感谢

好的,我必须创建自己的通知流程来处理401错误

首先,并非所有通知都适用于React 16.13.2

其次,“this is undefined”的错误消息来自catch内部,它不理解“this”是什么

第三,我必须使用异步类型,然后使用wait-for等待从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'));
import React,{Component}来自'React';
从“react dom”导入react dom;
导入“../css/app.scss”;
导入“引导”;
从“@material ui/core/TextField”导入TextField;
从“@material ui/core/Button”导入按钮;
从“jquery”导入美元;
导出类登录扩展组件{
建造师(道具){
超级(道具);
这个州={
电子邮件:“”,
密码:“”,
用户名:“”,
errorMsg:“”,
hasError:错误
};
this.handleClick=this.handleClick.bind(this);
}
componentDidMount(){
//console.log(React.version);
}
设置通知(参数){
//log('maketosetnotification func');
let notifications=$(“#notifications”);
通知。addClass(“警报危险”);
html(参数错误);
}
异步handleClick(){
常量请求选项={
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”,
“接受”:“应用程序/json”,
“凭证”:“同一来源”
},
正文:JSON.stringify({
“电子邮件”:this.state.email,
“密码”:this.state.password,
“用户名”:this.state.username
})
};
const response=wait fetch('/login',requestOptions);
const data=wait response.json();
this.setState({errorMsg:data.error});
这是一个设置通知(数据);
}
render(){
返回(
this.setState({username:event.currentTarget.value})
/>

this.setState({email:event.currentTarget.value}) />
this.setState({password:event.currentTarget.value}) />
this.handleClick()}> 登录 ); } } ReactDom.render(,document.getElementById('Login'));

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

顺便说一句,这只是一个div,我添加了一个“alert-alert-danger”类,并通过.html添加了内容。为了制作一个成功的版本,我将添加一个类o