0

I'm making a project that consists of separate frontend and backend. From the frontend, I make a POST request via fetch that should send a string 'ORANGE' to the backend and then the backend should log it to the console. I can't get the backend to console log the string. I looked at the request in devtools and the string 'ORANGE' was buried there under 'Request payload'. The request itself was sent alright. How do I actually access the string so I can do things with it? (eg, store in database)

//FRONTEND
const commentForm = document.getElementById("editform");
commentForm.addEventListener('submit', function(e) { 
    e.preventDefault();
    fetch('http://localhost:3000/posts/:id', {
        mode: 'cors',
        method: 'post',
        headers: {
            "Content-type": "text/plain;charset=UTF-8"
        },
        body: "ORANGE"
    }).then(function(response) {
        if (response.ok) {
            console.log("response.ok was true: "+ response)
        } else {
            let error = new Error(response.statusText)
            error.response = response
            throw error
        }
    })
});

//BACKEND
router.post('/posts/:id', function(req, res, next) {
    console.log('What do I put here to get ORANGE logged?!')
    //On the server side I tried some console.log tests.
    //console.log("req is " + req);               //req is [object Object]
    //console.log("type of req is " + typeof req); //type of req is object
    //console.log(JSON.parse(req)); //SyntaxError: unexpected token o in JSON at position 1  
    res.send('whatever. I want ORANGE.')
}
Krupal Panchal
  • 1,553
  • 2
  • 13
  • 26
rbkjefkj
  • 25
  • 7
  • What about `console.log(req.body)`?? – Subburaj Oct 18 '19 at 11:34
  • req.body is undefined – rbkjefkj Oct 18 '19 at 11:35
  • Express used to have a rawBody property on requests, but that's been removed, and now all request bodies are expected to be in JSON. If you want to send plain-text bodies, you'll have to implement your own middleware, as described in this answer: https://stackoverflow.com/a/12345876/2444210 – IceMetalPunk Oct 18 '19 at 11:40
  • you need to replace :id in http://localhost:3000/posts/:id with an actual id. – jperl Oct 18 '19 at 11:40
  • @jperl That will be necessary once the route does anything with that parameter, but that's not stopping the body from being available; it'll just bind req.params.id to the string `:id`. – IceMetalPunk Oct 18 '19 at 11:41

4 Answers4

0

Try for the following:

  1. Use body parser in your server.js file.

  2. Send post request as content-type as json as follows,

    headers: { Content-Type: application/json }

and body should be a JSON

body: {"color":"ORANGE"}

  1. In your route just print

    console.log(req.body.color)

Subburaj
  • 5,114
  • 10
  • 44
  • 87
0

Express won't, by default, process the body of a request. You need to load a module to do so explicitly.

Since you are using plain text, you can use the body-parser module. This will create a body property on the request:

const bodyParser = require('body-parser');
router.use(bodyParser.text({type: 'text/plain'}))
router.post('/posts/:id', function(req, res, next) {
    console.log(req.body);
    res.send('Response')
});

Note, however, that it is generally better to use a structured data format like JSON rather than plain text.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

In Express 4.16 body-parser module isn't necessary anymore. All you need for getting the body is:

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

Use "Content-type": "application/x-www-form-urlencoded" inside the fetch otherwise CORS will send preflights and give you a hard time. (for more on this google CORS simple request requirements).

rbkjefkj
  • 25
  • 7
-1

As in the documentation of fetch() explained:

This is just an HTTP response, not the actual JSON. To extract the JSON body content from the response, we use the json() method (defined on the Body mixin, which is implemented by both the Request and Response objects.)

const response = await fetch('http://example.com/movies.json');
const myJson = await response.json();
console.log(JSON.stringify(myJson));

so you don't have a body object inside your response, only a json object, which is your body.

HasBert
  • 113
  • 1
  • 9