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.