skip to Main Content

I try to use Fetch() API to post text/plain :

fetch('/test', {
    method: 'post',
    headers: {
      'Content-Type': 'text/plain'
    },
    body: "this is a test"
  })
 .then(response => response.text())
 .then(body => {
    console.log(body)
 })

This is the router that deal with the request

router.post('/test',(req,res)=>{
    console.log(req.body)
    res.send('OK')
})

However, the output of console.log(req.body) is {}.

I think the problem is the code after body: I don’t know what is the right way to post text/plain data.

2

Answers


  1. Here, bodyparser.text middleware will only parse the request coming with the type of text/plain.

    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    
    const PORT = 3000;
    
    app.use(bodyParser.text({
      type: 'text/plain'
    }));
    
    // DESC: Route to handle test
    // Method: POST
    // Access: PUBLIC
    app.post('/test', (req, res) => {
      console.log(req.body);
      res.send('OK');
    });
    
    app.listen(PORT, () => console.log(`Server is running at http://localhost:${PORT}`));
    Login or Signup to reply.
  2. Here are a few things you can try to troubleshoot the issue:

    Make sure you’re using a middleware like body-parser to parse the request body. Without it, the req.body object will be empty.

    const express = require('express');
    const bodyParser = require('body-parser');
    const app = express();
    
    // parse application/x-www-form-urlencoded
    app.use(bodyParser.urlencoded({ extended: false }));
    
    // parse application/json
    app.use(bodyParser.json());
    
    // your routes...
    

    You can try using FormData on the client-side to send the data as a multipart/form-data instead of text/plain.

    const formData = new FormData();
    formData.append('text', 'this is a test');
    
    fetch('/test', {
      method: 'post',
      body: formData
    })
    .then(response => response.text())
    .then(body => {
      console.log(body);
    });
    

    If you still want to use text/plain, you can try sending the data as a stringified JSON object.

    fetch('/test', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        text: 'this is a test'
      })
    })
    .then(response => response.text())
    .then(body => {
      console.log(body);
    });
    

    Then on the server-side, you can access the data with req.body.text.

    I hope this helps you solve the issue!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search