0

I would like to send data to a Node.js server running on localhost with ajax. To test this, I wanted to send the input of type text to the server and just log it there. This is my Post-Function (which is called by clicking on a button):

 function answer(){
                let data = {
                    name : $('#send').val()
                };
                console.log(data);
                $.ajax({
                    type: 'POST',
                    url: 'http://localhost:3456/MyWebApp/Test',
                    dataType: 'text',
                    data: data.name,
                    success: console.log('post was successfull'),
                    error: function(textStatus, errorTrown){
                        console.log(textStatus + " " + errorTrown);
                    }
                });
            }

On my Server I try to collect the data with the following function:

    app.post('/MyWebApp/Test', function(request,response){
        console.log(request.body.data);
    });
    
app.listen(3456);

My problem is, that the value on my server (in the above console.log) is always undefined. I already tried to send the whole json-Object with dataType-Parameter json instead of text, but then I get an error in my server for trying to read a property value of something undefined. How do I have to implement the app.post function, to make the data readable and work with it?

I hope it is possible to understand what I am trying to achieve and what my problem is, I dont really know much about Node.js or Ajax, still I would be thankful for any help.

DerWolferl
  • 71
  • 7

1 Answers1

0

You're sending one string value data.name so your http request Content-Type would be plain/text
At NodeJS side you're using express library and it doesn't provide post request body by default.
You need to collect post request body using "data" event

request.on("data", callback);
Plush
  • 1
  • If you want to parse **JSON** on express you need to use express json middleware `app.use(express.json())` – Plush Nov 26 '19 at 20:18