Dudu Dudu
Dudu Dudu

Reputation: 181

Post request from fetch gives a 404 server error (javascript/express)

I'm trying to see if a post request would work on my server at the '/db' route. The get request works just fine, but the 'Post' request gives a '404' not found error.

(Part of) my js code:

function getReq() {
    let p = fetch("http://localhost:3000/db").then((a)=>a.json()).then((x)=>console.log(x))
}

    async function postReq(obj) {
        console.log(obj)
        const p = await fetch("http://localhost:3000/db",
            {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: obj
            }
        )
    }

My express code:

const app = express();
app.use(bodyParser.json());

app.get('/db', (req,res)=>
{
    res.sendFile("db.json");
});

app.post("/db", function(req,res) 
{
    res.send("ok");
});

app.use(express.static('public'));
app.listen(3000, (ok) => console.log("Okk"));

db.json and app.js are in the same folder, and I only call postReq with json strings. The rest of the files are in the 'public' directory. Could anyone guide me to what I could be doing wrong? Thank you.

Upvotes: 0

Views: 832

Answers (1)

Batuhan
Batuhan

Reputation: 1611

You need to stringify the body because your content-type is application/json

async function postReq(obj) {
        console.log(obj)
        const p = await fetch("http://localhost:3000/db",
            {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(obj) // Here 
            }
        )
    }

Upvotes: 2

Related Questions