1

I have tried to post data in postman and it returns a json object , the methods are working good . I have a problem to get the value of attribut when the api respond with a json object . the forma of json like this :

{
 "success" : "true"
}

the api method :


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();
});

the post method from a react app is :

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

}


the data declaration in state : data:[] the error is that the data is undefined .

azdeviz
  • 597
  • 2
  • 9
  • 20
  • Have a look [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) `.then(response => response.json()).then(data => ...` – devserkan May 15 '20 at 22:02
  • Does this answer your question? [Using Fetch API to Access JSON](https://stackoverflow.com/questions/37663674/using-fetch-api-to-access-json) – devserkan May 15 '20 at 22:03
  • thanks for reply , the method you mention is true and works , but I have problem with `response.json()` it shows me **Unhandled Rejection (SyntaxError): Unexpected end of input** every time I use it. – azdeviz May 15 '20 at 23:45

2 Answers2

0

when you do an api call using fetch request, it returns a promise that contains the response and that response is resolved by the first .then(). after resolving this first promise it returns another response and you need to resolve it with another .then()

Please check the working example below:

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;
Khabir
  • 5,370
  • 1
  • 21
  • 33
  • thanks for reply , the method you mention is true and works , but I have problem with `response.json()` it shows me **Unhandled Rejection (SyntaxError): Unexpected end of input** – azdeviz May 15 '20 at 23:45
  • @AzizMobarak, pls remove `mode: 'no-cors' ` for more detail please see https://stackoverflow.com/questions/43317967/handle-response-syntaxerror-unexpected-end-of-input-when-using-mode-no-cors/43319482#43319482 – Khabir May 16 '20 at 00:01
  • I got ` TypeError: Failed to fetch` when removing no-cors , note that I m using POST method and I want to get response values and not get. thanks. – azdeviz May 16 '20 at 00:47
0

there is two problems here at this example with both parts api and react app , the first thing I did is to understand cors and how it works in express and I found that I should do the following steps to the api :

run

npm install cors

second is to add

const cors =require('cors')

and then :

app.use(cors());

and last step is inside the router post I should add cors :

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

about react app code it just need to remove module="no-cors"

and then it works .

azdeviz
  • 597
  • 2
  • 9
  • 20