Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

291
Views
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.

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)
});

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!