Zoolu
Zoolu

Reputation: 39

can't get success response data/status from node/express to my client app(react): "referenceerror response is not defined"

i've made a basic node/express server, and have a route that handles submission of form data(i've made using react), the post request is handled using async/await with fetch api.. i'm not sure if the issue is with my server-side route or my implementation of the post request with async/await fetch. however the server does receive the form data it just doesn't return a response.

my code:

node/express route

router.post('/add', function (req, res) {
    console.log(req.body);
    res.json({success : "Updated Successfully", status : 200});
});

note: the console.log(prints the expected data, but the response isn't being picked up by client correcly)

post request implementation:

const postRequestHelper = async (routePath, objectPayload) => {
    console.log("posting payload object: ");
    console.log(objectPayload);
    const rawResponse = await fetch(routePath, {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(objectPayload)
    });
    const response = await rawResponse.json();
    return response;
};

export default postRequestHelper;

form submission code where post request is called:

async handleSubmit(event) {
    if(typeof this.state.validationMessages === "undefined"){

        // create payload data object
        let objectPayload = Object.assign({}, this.state);
        for(let key in objectPayload){
            if(!isInObject(key, formKeyConstants)) // delete any prop keys that aren't in formPropertyKeys js file
                delete objectPayload[key]
        }

        // send post request
        console.log(objectPayload);
        const response = await postRequestHelper("http://localhost:8080/user/add", objectPayload);

        // log response data
        console.log("response");
        console.log(response);
    }
    event.preventDefault();
}

Upvotes: 0

Views: 771

Answers (3)

remote007
remote007

Reputation: 57

  • If routing takes place in app , then use :

       app.use(express.json)
    
  • If routing takes place in router folder , then use :

       router.use(express.json)
    

It'll by default uncover the req.body into json format.(For which installing and initializing express is a must)

Upvotes: 0

Zoolu
Zoolu

Reputation: 39

issue was with async await fetch api it seems, issue with await was breaking the response from the server.

Upvotes: 0

cperez08
cperez08

Reputation: 749

What about trying in your server return res.send(JSON.stringify({success : "Updated Successfully", status : 200}));

Upvotes: 1

Related Questions