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

168
Vistas
Javascript POST fetch to Express.js server returning 405 (method not allowed)

I'm trying to build an application with Node and Express, and in the script.js file I specify a fetch request to the API POST route I defined, which looks like this:

//Post to the database with a fetch request
fetch("/api/characters", {
    method: "POST",
    headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
    },
    body: JSON.stringify(character),
  })
  .then(response => {
        if (response.ok) {
          return response.json();
        }
        alert("Error "+response.statusText);
      });

The route I defined in server.js looks like this:

//POST a character to the database
app.post("/api/characters", (req, res) => {
let character = req.body;

//Get the db.json file
fs.readFile(path.join(__dirname, "/db/characters.json"), "utf8", (err, data) => {
    if (err) {
        throw err;
    }
    if (data) {
        let charactersArray = JSON.parse(data);
        
        charactersArray.push(character);
    }

fs.writeFileSync(path.join(__dirname, "/db/characters.json"), JSON.stringify(charactersArray, null, 4), (err) => {
    if (err) {
        throw err;
    }
    console.log("Successfully wrote character to db");
});

res.send("Successfully wrote character to db");

});
});

I tested the POST route in Insomnia earlier and it looks like it works, so I'm fairly certain the problem lies in the fetch request, but it looks to me like the path and method supplied are correct, so I'm not sure why the POST is saying that it isn't allowed.

about 4 years ago · Juan Pablo Isaza
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