0
votes

This is the react fetch:


   var json = {
     json: JSON.stringify({
         a: 1,
         b: 2
     }),
     delay: 3
 };

fetch('/saveInfo', {
         method: 'post',
         headers: {
             'Accept': 'application/json, text/plain, */*',
             'Content-Type': 'application/json'
         },

         body:  JSON.stringify(json.json)
     })
     .then(function (response) {
         return response.json();
     })
     .then(function (result) {
         alert(result);
          console.log("The file was saved!");
     })
     .catch (function (error) {
         console.log('Request failed');
     });

This is node:

<pre>
var express = require('express');

module.exports = function(app) {
  var router = express.Router();

  router.get('/', function (req, res) {
    console.log('from node');
    console.log(req);


    res.json({status: 'UP'});
  });

  app.use("/saveInfo", router);
}
</pre>

The code above doesn't work with the 2nd parameter to the fetch.

But when I execute it w/o the second parameter to fetch as below:

fetch('/saveInfo')
     .then(function (response) {
         return response.json();
     })
     .then(function (result) {
         alert(result);
          console.log("The file was saved!");
     })
     .catch (function (error) {
         console.log('Request failed');
     });

Works fine and is able to communicate to the node program.

Can any one help me with this what is wrong. I wanted to send the react's UI forms state t the node program.

1

1 Answers

0
votes

You need to add a handler for the POST requests also.
In the fetch method for 1st case, you have given the method type as POST but node doesn't have any handling for that.
However, when you don't give the second parameter, it is considered as GET request and is intercepted by router.get.
Just add this in the node (before app.use line):

router.post("/", function (req, res) {
  console.log('from node');
  console.log(req);
  res.json({status: 'UP'});
});

It will enable node to listen for POST requests.

Edit: To have access to post request body params in router.post, you need body-parser package. Install this package and add these two lines before initializing the express router:

app.use(bodyParser.json())  
app.use(bodyParser.urlencoded({ extended: false }))

Read http://jilles.me/express-routing-the-beginners-guide/ for detailed explanation