简体   繁体   中英

Passing res.send value from node.js backend to react.js

I am trying to pass a string from nodejs backend using res.send

app.post("/user", (req,res) => {
console.log(req.body.email);
res.send('haha');
});

I want to perform some operations based on the retrieved string value on the front end.

axios({ 
        method: 'post', 
        url: '/user', 
        data: { email: this.state.emailFetch } 
        }).then(response => {
            if(response.send == "haha")
            {
                return <Redirect to="/"/> 
            }
        });

I think I'm messing up at the handling of response at the front end. Can anyone guide me though?

Try response.data , res.send() is just the function to send the response. You can also console log the whole response to check where the response value is stored.

Your axios code should be like:

axios({ 
    method: 'post', 
    url: '/user', 
    data: { email: this.state.emailFetch } 
    }).then(response => {
        if(response.data == "haha")
        {
            return <Redirect to="/"/> 
        }
    });

You should read axios doc. And if you are trying to create an API you should use res.json([]) instead in most cases

response.send is a method, so you cannot use it in frontend to extract data from it. Easiest way for you to see whats happening on frontend side, is just console.log(response) and you can see how your response is structured and where data is contained.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM