Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 => {
    ...
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading