1

I'm posting the data {id: "abc123", text: "sometext"} to a node API. Posting from a component with action call:

export function addTextToAPI(inputData) {
    return(dispatch) => {
        console.log(inputData),
        dispatch(addText(inputData))
         fetch(myapi, { 
            headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
            },
            method: 'POST',
            data:  inputData
      })
        .then(res => res.json())
    }
}

console.log(inputData) is {id: "abc123", text: "sometext"}

node:

var express    = require('express');
var bodyParser = require('body-parser');

var app = express();

app.use(bodyParser.json());

app.post('/addtest', (req, res) => {

    console.log(req.body);        // <= returns blank object {}

    console.log(req.body.data);   // <= returns undefined

    console.log(req.query);       // <= returns blank object {}

    console.log("test added");      

});


app.listen(3000);

I want to be able to read the inputData in req. How do I do that? I want to be able to read the inputData in req. How do I do that?

3
  • I've also tried JSON.stringify(inputdata) but it doesn't work. Commented Sep 15, 2017 at 23:20
  • What is your content-type request header? Commented Sep 15, 2017 at 23:21
  • @Phix .. Updated the fetch in question. Please have a look. Commented Sep 15, 2017 at 23:25

1 Answer 1

3

To post data you need to pass in a body param to fetch.

This should work:

export function addTextToAPI(inputData) {
    return(dispatch) => {
        console.log(inputData),
        dispatch(addText(inputData))
         fetch(myapi, { 
            headers: {
               'Accept': 'application/json',
               'Content-Type': 'application/json'
            },
            method: 'POST',
            body: JSON.stringify(inputData)
      })
        .then(res => res.json())
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

passing body doesn't work. Now I'm not even getting any console logs from node. Changing back to data console log is working. I thing passing body doesn't call node at all.
try JSON.stringify ing inputData and passing it as body
That worked! JSON.stringify did the trick. Why do I need to add body and can't pass it like any other param?
This is in the fetch spec, meaning it is just how the api is designed - you have to pass a body.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.