为什么我无法从api获取正确的值

编程入门 行业动态 更新时间:2024-10-16 18:36:41

为什么我无法从api获取<a href=https://www.elefans.com/category/jswz/34/1771142.html style=正确的值"/>

为什么我无法从api获取正确的值

我已经尝试在postman中发布数据,并且它返回一个json对象,这些方法运行良好。当api用json对象响应时,我很难获得属性值。json的格式如下:

{
 "success" : "true"
}

api方法:


router.post("/sickers/user/login/", (req, res) => {
    var values = JSON.parse(req.body);
    var pass = values.password;
    var email = values.email;
    //console.log(values);
    if (pass !== null || pass !== "") {
        try {
            con.connect();
            con.query("SELECT Password FROM `sickers` WHERE Email='" + email + "'", function(err, rows, field) {
                if (err) {
                    console.log(err);
                    res.send("an error detected try later");
                } else {
                    try {
                        if (pass == rows[0].Password) {

                            //trying to send correct message from here
                            res.send({ success: "true" });
                            console.log("yes")
                        } else {

                            console.log("no")
                            res.send({ success: "false" });
                        }
                    } catch {

                        console.log("no")
                        res.send({ success: "false" });
                    }

                }
            });
        } catch (e) {

            res.send("no data found");
            console.log("obj not found");
        }
    }
con.end();
});

React应用程序的发布方法是:

//submit values
async submithandler(e) {
    e.preventDefault();
   try{
   await fetch('http://localhost:8000/api/sickers/user/login/',{
     method:'post',
     mode:'no-cors',
     headers:{
         'Accept':'application/json',
         'Content-type': 'application/json'
     },
     body:JSON.stringify({
           password:this.state.password,
           email:this.state.email
     })
    })
    .then(response=>{
        this.setState({data:response})
        alert(data.success);
    })

    }catch(e){
        alert(e)
    }

}


处于状态的数据声明:data:[]错误是数据未定义。

回答如下:

当您使用fetch请求进行api调用时,它返回一个promise,其中包含response,并且response由第一个。then()解析。 。解决此first promise之后,它会返回另一个response,您需要使用另一个。then()

来解决它

请检查下面的工作示例:

import React, {Component} from "react";

class FetchExample extends React.Component {
    state = {
        isLoading: false,
        questions: [],
        error: null
    };

    fetchQuestions = () => {
        fetch(`https://opentdb/api.php?amount=10&difficulty=hard&type=boolean`,)
            .then(response => {
                    if (response.status !== 200) {
                        console.log('There was a problem. Status Code: ' + response.status);
                        return;
                    }
                    response.json().then(data => {
                        console.log(data);
                        this.setState({
                            questions: data,
                            isLoading: false
                        })
                    });
                }
            )
            .catch(function (error) {
                console.log('Error: ', error);
                this.setState({error, isLoading: false})
            });
    };

    render() {
        const {isLoading, questions, error} = this.state;
        return (
            <React.Fragment>
                <h1>Random Question</h1>
                <button onClick={this.fetchQuestions}>Click for calling API using fetch</button>
                {error ? <p>{error.message}</p> : null}

                {!isLoading && questions.results ? (
                    questions.results.map((questions, index) => {    //something right here
                        //is erroring
                        const {question, category, type, difficulty} = questions;
                        return (
                            <div key={index}>
                                <p>Question: {question}</p>
                                <p>Question Type: {type}</p>
                                <p>Difficulty: {difficulty}</p>
                                <hr/>
                            </div>
                        );
                    })
                ) : isLoading ? (
                    <h3>Loading...</h3>
                ) : null}
            </React.Fragment>
        );
    }
}

export default FetchExample;

更多推荐

为什么我无法从api获取正确的值

本文发布于:2024-05-07 16:04:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1757044.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正确   api

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!