0

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.

1 Answer 1

2

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 
            }
        )
    }
Sign up to request clarification or add additional context in comments.

3 Comments

The obj passed as a parameter is already a json string, that's why i didnt stringify it again
It is not JSON string it is Javascript Object. stringify() is used to convert JSON to JSON String. It serializes a JavaScript object into a JSON String. You have to send the body as stringified JSON for the conversion for the backend. This is restriction of content-type: application/json
@DuduDudu Possibly test code passed a primitive (JavaScript) string to postReq as its argument. In general JavaScript string values are not valid JSON text, although on occasion they can be. If you did pass valid JSON text to postReq, please update the question with details because this answer does remove the 404 error generated by bodyParser middleware.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.