node.js: The POST method in my RESTAPI does not work

Issue

I start learning Node.js and Express.js and I’m trying to create a simple API to list data from JSON file (using the GET method) and add a new user using the POST method.

the GET method works fine but the POST method does not work

when I request http://127.0.0.1:8080/listusers the API sends all users in a JSON file.
when I request http://127.0.0.1:8080/adduser the API has to add new User Info and send the new data back to the browser.

NOTE: I read all the questions on Stackoverflow about this problem but
non of them help me so I have to ask again.

the problem is when I request http://127.0.0.1:8080/adduser I get the following error

Cannot GET /adduser

here is the server.js:

var express = require('express');
var app = express();
var fs = require('fs');

var user = {
        "user4" : {
               "name" : "mounir",
       "password" : "password4",
       "profession" : "teacher",
       "id": 4
    }
};

app.post('/adduser', function (req, res) {
        // First read existing users.
        fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
               data = JSON.parse( data );
               data["user4"] = user["user4"];
               console.log( data );
       res.end(JSON.stringify(data) );
    });
});

app.get('/listusers', function (req, res) {
    fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
        console.log(data);
        res.end(data);
    });
});

var server = app.listen(8080, function () {
    var host = server.address().address;
    var port = server.address().port;
    console.log("listening at http://%s:%s", "0.0.0.0", port)
});

Solution

The answer is in the error. Cannot GET /adduser. Keyword GET! If you are making a post request, be sure you include the appropriate headers and that you are making a POST request, with a body, and not a GET request. For instance if you are using fetch:

const myInit = {
  method: 'POST',
  headers: myHeaders,
  body: {
    ...
  }
};

fetch("http://127.0.0.1:8080/adduser", myInit)
  .then(res => {
    ...
  });

Answered By – FODpatrick

Answer Checked By – Senaida (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.