Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

169
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda