简体   繁体   中英

node js post request only returning undefined

I'm trying to make an api call for an online course project but before I can do that I need to retrieve the user input and currently I'm getting undefined responses to my post request. I think these are the relevant parts of my code:

formHandler.js:


import { postURL } from "./postURL"

function handleSubmit(event) {
    event.preventDefault()

    // check what text was put into the form field
    let url = document.getElementById('URL').value
    postURL('/postURL', url)
    //.then(updateUI());
};

export { handleSubmit }

postURL.js:

let postURL = async(url = '', data = {})=>{
    let response = await fetch(url, {
        method: 'POST',
        credentials: 'same-origin',
        headers: {
            "Content-Type": 'application/json',
        },
        body: JSON.stringify( { data} ),
    });
    try {
        console.log(data);
    }catch(error){
        console.log("error", error);
    }
}

export { postURL }

part of index.html:

<form class="form" onsubmit="return Client.handleSubmit(event)">
    <input id="URL" type="text" name="input" value="" placeholder="URL" size="48">
    <input type="submit" id="input" class="button" name="" value="submit" onclick="return Client.handleSubmit(event)" onsubmit="return Client.handleSubmit(event)">
</form>

index.js on server side:

app.post('/postURL', getURL);

function getURL(req, res){
    console.log(req.body);
    url = req.body;
    console.log(url)
    //apiCall(url)
}

Do you have any idea why the data isn't being returned to /postURL? I can't figure this out. Any help would be greatly appreciated.

Thank you, Mike

I am not sure if you are receiving undefined in client or server. If you want to receive JSON data in backend, you have to use bodyParser.json in express. If you want to receive a response in client, just call res.json(your_value), or res.send(yourValue)

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