POSTing json to express using jQuery

后端 未结 1 1090
忘了有多久
忘了有多久 2021-02-07 00:19

I\'m having an issue when sending JSON data from my client to a node server running express.

Here\'s a simple server that demonstrates my issue:

var expr         


        
相关标签:
1条回答
  • 2021-02-07 00:51

    $.post sends url-encoded data, so what is really sent is number=1, which then is parsed as well as it can by bodyParser middleware.

    To send json you have to use JSON.stringify({number:1}).

    Using $.post unfortunately won't set the appropriate Content-Type header (express will handle it anyway), so it's better to use:

    $.ajax({
        url: '/', 
        type: 'POST', 
        contentType: 'application/json', 
        data: JSON.stringify({number:1})}
    )
    
    0 讨论(0)
提交回复
热议问题