Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

298
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda