Empty body in fetch post request












2















i'm struggling with the fetch API in javascript.
When i try to POST something to my server with fetch, the request body an empty array. But when i use Postman it works...
Here is my server code in NodeJS :



const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.post('/api', function (req, res) {
console.log(req.body)
})
app.listen(port)


and here is my client:



fetch('http://"theserverip":3000/api', {
method: 'POST',
headers: { "Content-Type": "application/json" },
mode: 'no-cors',
body: JSON.stringify({
name: 'dean',
login: 'dean',
})
})
.then((res) => {
console.log(res)
})


The problem is that on the SERVER side, the req.body is empty.
Can someone help me? Thank you !










share|improve this question

























  • Are you saying that the response from your express server is empty? Or is the request on the server empty?

    – skellertor
    Jan 3 at 3:50











  • The request on the server is empty.

    – Trietch
    Jan 3 at 4:11






  • 1





    seems a valid request, your server might be unable to parse it. check on server what it is expecting.

    – Just code
    Jan 3 at 4:22











  • Why mode: 'no-cors'?

    – Phil
    Jan 3 at 4:33






  • 1





    I use no-cors mode because without it i have a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error. But I just saw your response, thank you i will investigate on how to solve this error without using this mode.

    – Trietch
    Jan 3 at 4:40
















2















i'm struggling with the fetch API in javascript.
When i try to POST something to my server with fetch, the request body an empty array. But when i use Postman it works...
Here is my server code in NodeJS :



const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.post('/api', function (req, res) {
console.log(req.body)
})
app.listen(port)


and here is my client:



fetch('http://"theserverip":3000/api', {
method: 'POST',
headers: { "Content-Type": "application/json" },
mode: 'no-cors',
body: JSON.stringify({
name: 'dean',
login: 'dean',
})
})
.then((res) => {
console.log(res)
})


The problem is that on the SERVER side, the req.body is empty.
Can someone help me? Thank you !










share|improve this question

























  • Are you saying that the response from your express server is empty? Or is the request on the server empty?

    – skellertor
    Jan 3 at 3:50











  • The request on the server is empty.

    – Trietch
    Jan 3 at 4:11






  • 1





    seems a valid request, your server might be unable to parse it. check on server what it is expecting.

    – Just code
    Jan 3 at 4:22











  • Why mode: 'no-cors'?

    – Phil
    Jan 3 at 4:33






  • 1





    I use no-cors mode because without it i have a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error. But I just saw your response, thank you i will investigate on how to solve this error without using this mode.

    – Trietch
    Jan 3 at 4:40














2












2








2


0






i'm struggling with the fetch API in javascript.
When i try to POST something to my server with fetch, the request body an empty array. But when i use Postman it works...
Here is my server code in NodeJS :



const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.post('/api', function (req, res) {
console.log(req.body)
})
app.listen(port)


and here is my client:



fetch('http://"theserverip":3000/api', {
method: 'POST',
headers: { "Content-Type": "application/json" },
mode: 'no-cors',
body: JSON.stringify({
name: 'dean',
login: 'dean',
})
})
.then((res) => {
console.log(res)
})


The problem is that on the SERVER side, the req.body is empty.
Can someone help me? Thank you !










share|improve this question
















i'm struggling with the fetch API in javascript.
When i try to POST something to my server with fetch, the request body an empty array. But when i use Postman it works...
Here is my server code in NodeJS :



const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.post('/api', function (req, res) {
console.log(req.body)
})
app.listen(port)


and here is my client:



fetch('http://"theserverip":3000/api', {
method: 'POST',
headers: { "Content-Type": "application/json" },
mode: 'no-cors',
body: JSON.stringify({
name: 'dean',
login: 'dean',
})
})
.then((res) => {
console.log(res)
})


The problem is that on the SERVER side, the req.body is empty.
Can someone help me? Thank you !







javascript node.js http express fetch






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 3 at 4:12







Trietch

















asked Jan 3 at 3:43









TrietchTrietch

336




336













  • Are you saying that the response from your express server is empty? Or is the request on the server empty?

    – skellertor
    Jan 3 at 3:50











  • The request on the server is empty.

    – Trietch
    Jan 3 at 4:11






  • 1





    seems a valid request, your server might be unable to parse it. check on server what it is expecting.

    – Just code
    Jan 3 at 4:22











  • Why mode: 'no-cors'?

    – Phil
    Jan 3 at 4:33






  • 1





    I use no-cors mode because without it i have a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error. But I just saw your response, thank you i will investigate on how to solve this error without using this mode.

    – Trietch
    Jan 3 at 4:40



















  • Are you saying that the response from your express server is empty? Or is the request on the server empty?

    – skellertor
    Jan 3 at 3:50











  • The request on the server is empty.

    – Trietch
    Jan 3 at 4:11






  • 1





    seems a valid request, your server might be unable to parse it. check on server what it is expecting.

    – Just code
    Jan 3 at 4:22











  • Why mode: 'no-cors'?

    – Phil
    Jan 3 at 4:33






  • 1





    I use no-cors mode because without it i have a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error. But I just saw your response, thank you i will investigate on how to solve this error without using this mode.

    – Trietch
    Jan 3 at 4:40

















Are you saying that the response from your express server is empty? Or is the request on the server empty?

– skellertor
Jan 3 at 3:50





Are you saying that the response from your express server is empty? Or is the request on the server empty?

– skellertor
Jan 3 at 3:50













The request on the server is empty.

– Trietch
Jan 3 at 4:11





The request on the server is empty.

– Trietch
Jan 3 at 4:11




1




1





seems a valid request, your server might be unable to parse it. check on server what it is expecting.

– Just code
Jan 3 at 4:22





seems a valid request, your server might be unable to parse it. check on server what it is expecting.

– Just code
Jan 3 at 4:22













Why mode: 'no-cors'?

– Phil
Jan 3 at 4:33





Why mode: 'no-cors'?

– Phil
Jan 3 at 4:33




1




1





I use no-cors mode because without it i have a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error. But I just saw your response, thank you i will investigate on how to solve this error without using this mode.

– Trietch
Jan 3 at 4:40





I use no-cors mode because without it i have a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error. But I just saw your response, thank you i will investigate on how to solve this error without using this mode.

– Trietch
Jan 3 at 4:40












3 Answers
3






active

oldest

votes


















7














The issue is



mode: 'no-cors'


From the documentation...




Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers




The simple content-type header restriction allows





  • text/plain,


  • application/x-www-form-urlencoded, and

  • multipart/form-data


This causes your nicely crafted Content-Type: application/json header to become content-type: text/plain (at least when tested through Chrome).



Since your Express server is expecting JSON, it won't parse this request.



I recommend omitting the mode config. This uses the default "cors" option instead.





Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.



Another (slightly hacky) option is to tell Express to parse text/plain requests as JSON. This allows you to send JSON strings as simple requests which can also avoid a pre-flight OPTIONS request, thus lowering the overall network traffic...



app.use(express.json({
type: ['application/json', 'text/plain']
})





share|improve this answer





















  • 1





    With the CORS middleware, it works!

    – Trietch
    Jan 3 at 4:49











  • Nice work @Phil!

    – skellertor
    Jan 3 at 5:06



















2














Please see document mode, no-cors mode only send simple headers. So the content-Type is changed to text/html; instead of application/json so your server can't recognize body format and return empty.



Remove mode: 'no-cors', and you should be fine.






share|improve this answer































    0














    If you want to get response using fetch consider to use res.send:



        app.post('/api', function (req, res) {
    res.send(req.body)
    })





    share|improve this answer



















    • 1





      Sorry if i did not make myself clear, but i don't want a response for the client, i just want the JSON to be sent to the server.

      – Trietch
      Jan 3 at 4:08













    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016068%2fempty-body-in-fetch-post-request%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    7














    The issue is



    mode: 'no-cors'


    From the documentation...




    Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers




    The simple content-type header restriction allows





    • text/plain,


    • application/x-www-form-urlencoded, and

    • multipart/form-data


    This causes your nicely crafted Content-Type: application/json header to become content-type: text/plain (at least when tested through Chrome).



    Since your Express server is expecting JSON, it won't parse this request.



    I recommend omitting the mode config. This uses the default "cors" option instead.





    Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.



    Another (slightly hacky) option is to tell Express to parse text/plain requests as JSON. This allows you to send JSON strings as simple requests which can also avoid a pre-flight OPTIONS request, thus lowering the overall network traffic...



    app.use(express.json({
    type: ['application/json', 'text/plain']
    })





    share|improve this answer





















    • 1





      With the CORS middleware, it works!

      – Trietch
      Jan 3 at 4:49











    • Nice work @Phil!

      – skellertor
      Jan 3 at 5:06
















    7














    The issue is



    mode: 'no-cors'


    From the documentation...




    Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers




    The simple content-type header restriction allows





    • text/plain,


    • application/x-www-form-urlencoded, and

    • multipart/form-data


    This causes your nicely crafted Content-Type: application/json header to become content-type: text/plain (at least when tested through Chrome).



    Since your Express server is expecting JSON, it won't parse this request.



    I recommend omitting the mode config. This uses the default "cors" option instead.





    Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.



    Another (slightly hacky) option is to tell Express to parse text/plain requests as JSON. This allows you to send JSON strings as simple requests which can also avoid a pre-flight OPTIONS request, thus lowering the overall network traffic...



    app.use(express.json({
    type: ['application/json', 'text/plain']
    })





    share|improve this answer





















    • 1





      With the CORS middleware, it works!

      – Trietch
      Jan 3 at 4:49











    • Nice work @Phil!

      – skellertor
      Jan 3 at 5:06














    7












    7








    7







    The issue is



    mode: 'no-cors'


    From the documentation...




    Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers




    The simple content-type header restriction allows





    • text/plain,


    • application/x-www-form-urlencoded, and

    • multipart/form-data


    This causes your nicely crafted Content-Type: application/json header to become content-type: text/plain (at least when tested through Chrome).



    Since your Express server is expecting JSON, it won't parse this request.



    I recommend omitting the mode config. This uses the default "cors" option instead.





    Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.



    Another (slightly hacky) option is to tell Express to parse text/plain requests as JSON. This allows you to send JSON strings as simple requests which can also avoid a pre-flight OPTIONS request, thus lowering the overall network traffic...



    app.use(express.json({
    type: ['application/json', 'text/plain']
    })





    share|improve this answer















    The issue is



    mode: 'no-cors'


    From the documentation...




    Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers




    The simple content-type header restriction allows





    • text/plain,


    • application/x-www-form-urlencoded, and

    • multipart/form-data


    This causes your nicely crafted Content-Type: application/json header to become content-type: text/plain (at least when tested through Chrome).



    Since your Express server is expecting JSON, it won't parse this request.



    I recommend omitting the mode config. This uses the default "cors" option instead.





    Since your request is not simple, you'll probably want to add some CORS middleware to your Express server.



    Another (slightly hacky) option is to tell Express to parse text/plain requests as JSON. This allows you to send JSON strings as simple requests which can also avoid a pre-flight OPTIONS request, thus lowering the overall network traffic...



    app.use(express.json({
    type: ['application/json', 'text/plain']
    })






    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Jan 3 at 4:55

























    answered Jan 3 at 4:36









    PhilPhil

    99.3k12145163




    99.3k12145163








    • 1





      With the CORS middleware, it works!

      – Trietch
      Jan 3 at 4:49











    • Nice work @Phil!

      – skellertor
      Jan 3 at 5:06














    • 1





      With the CORS middleware, it works!

      – Trietch
      Jan 3 at 4:49











    • Nice work @Phil!

      – skellertor
      Jan 3 at 5:06








    1




    1





    With the CORS middleware, it works!

    – Trietch
    Jan 3 at 4:49





    With the CORS middleware, it works!

    – Trietch
    Jan 3 at 4:49













    Nice work @Phil!

    – skellertor
    Jan 3 at 5:06





    Nice work @Phil!

    – skellertor
    Jan 3 at 5:06













    2














    Please see document mode, no-cors mode only send simple headers. So the content-Type is changed to text/html; instead of application/json so your server can't recognize body format and return empty.



    Remove mode: 'no-cors', and you should be fine.






    share|improve this answer




























      2














      Please see document mode, no-cors mode only send simple headers. So the content-Type is changed to text/html; instead of application/json so your server can't recognize body format and return empty.



      Remove mode: 'no-cors', and you should be fine.






      share|improve this answer


























        2












        2








        2







        Please see document mode, no-cors mode only send simple headers. So the content-Type is changed to text/html; instead of application/json so your server can't recognize body format and return empty.



        Remove mode: 'no-cors', and you should be fine.






        share|improve this answer













        Please see document mode, no-cors mode only send simple headers. So the content-Type is changed to text/html; instead of application/json so your server can't recognize body format and return empty.



        Remove mode: 'no-cors', and you should be fine.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 3 at 4:38









        yip102011yip102011

        36218




        36218























            0














            If you want to get response using fetch consider to use res.send:



                app.post('/api', function (req, res) {
            res.send(req.body)
            })





            share|improve this answer



















            • 1





              Sorry if i did not make myself clear, but i don't want a response for the client, i just want the JSON to be sent to the server.

              – Trietch
              Jan 3 at 4:08


















            0














            If you want to get response using fetch consider to use res.send:



                app.post('/api', function (req, res) {
            res.send(req.body)
            })





            share|improve this answer



















            • 1





              Sorry if i did not make myself clear, but i don't want a response for the client, i just want the JSON to be sent to the server.

              – Trietch
              Jan 3 at 4:08
















            0












            0








            0







            If you want to get response using fetch consider to use res.send:



                app.post('/api', function (req, res) {
            res.send(req.body)
            })





            share|improve this answer













            If you want to get response using fetch consider to use res.send:



                app.post('/api', function (req, res) {
            res.send(req.body)
            })






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jan 3 at 3:55









            chau giangchau giang

            697




            697








            • 1





              Sorry if i did not make myself clear, but i don't want a response for the client, i just want the JSON to be sent to the server.

              – Trietch
              Jan 3 at 4:08
















            • 1





              Sorry if i did not make myself clear, but i don't want a response for the client, i just want the JSON to be sent to the server.

              – Trietch
              Jan 3 at 4:08










            1




            1





            Sorry if i did not make myself clear, but i don't want a response for the client, i just want the JSON to be sent to the server.

            – Trietch
            Jan 3 at 4:08







            Sorry if i did not make myself clear, but i don't want a response for the client, i just want the JSON to be sent to the server.

            – Trietch
            Jan 3 at 4:08




















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54016068%2fempty-body-in-fetch-post-request%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Mossoró

            Error while reading .h5 file using the rhdf5 package in R

            Pushsharp Apns notification error: 'InvalidToken'