【问题标题】:Why I can't get the correct value from api为什么我无法从 api 获得正确的值
【发布时间】:2020-09-01 20:31:58
【问题描述】:

我尝试在邮递员中发布数据,它返回一个 json 对象,这些方法运行良好。 当 api 以 json object 响应时,我在获取属性值时遇到问题。 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 应用的 post 方法是:

//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)
    }

}


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

【问题讨论】:

  • 看看here.then(response => response.json()).then(data => ...
  • 这能回答你的问题吗? Using Fetch API to Access JSON
  • 感谢您的回复,您提到的方法是正确的并且有效,但我对 response.json() 有疑问,它向我显示 Unhandled Rejection (SyntaxError): Unexpected end of input 每个我用它的时间。

标签: node.js reactjs api


【解决方案1】:

在这个例子中, api 和 react app 都有两个问题, 我做的第一件事是了解 cors 以及它是如何在 express 中工作的,我发现我应该对 api 执行以下步骤:

运行

npm install cors

第二个是添加

const cors =require('cors')

然后:

app.use(cors());

最后一步是在路由器帖子中我应该添加cors:

router.post('path',cors(),(req,res)....

关于 react 应用代码只需要删除 module="no-cors"

然后它就起作用了。

【讨论】:

    【解决方案2】:

    当您使用 fetch 请求进行 api 调用时,它会返回一个 promise,其中包含 responseresponse 由第一个 .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.com/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;
    

    【讨论】:

    • 感谢您的回复,您提到的方法是正确的并且有效,但我对response.json() 有问题,它告诉我未处理的拒绝(SyntaxError):输入意外结束
    • @AzizMobarak,请删除 mode: 'no-cors' 了解更多详情,请参阅 stackoverflow.com/questions/43317967/…
    • 删除 no-cors 时出现 `TypeError: Failed to fetch`,请注意我正在使用 POST 方法,我想获取响应值而不是获取。谢谢。
    猜你喜欢
    • 2011-08-19
    • 1970-01-01
    • 2021-12-02
    • 2015-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    相关资源
    最近更新 更多