简体   繁体   中英

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

尝试在服务器中return res.send(JSON.stringify({success : "Updated Successfully", status : 200}));

似乎是async await fetch api的问题,而await的问题则破坏了服务器的响应。

  • 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)

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