0

I'm trying to learn express and front javascript. I am trying to pass json data via post request with fetch API and want to take in on backend with express. My backend code looks like this:

const express = require('express');
const app = express();
const path = require('path');

app.get('/log', function(req, res){
    console.log("Hi");
});

app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
app.listen(3000, () => console.log('Example app listening on port 3000!'));

and my index.html file looks like this:

<!DOCTYPE html>
<html>
<head>
<title>Fetch And Express Test</title>
</head>
<body>

    <input id="a">
    <input id="b">
    <button> Click</button>
    <script>
        document.getElementsByTagName("button")[0].addEventListener("click",function(){
            console.log("Here");
            let aInput = document.getElementById("a").value;
            let bInput = document.getElementById("b").value;

            let json = {"a": aInput, "b": bInput};
            var data = new FormData();
            data.append( "json", JSON.stringify(json));

            fetch('http://localhost:3000/log', {
                method: "POST", // *GET, POST, PUT, DELETE, etc.
                mode: "cors", // no-cors, cors, *same-origin
                cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
                credentials: "same-origin", // include, same-origin, *omit
                headers: {
                    "Content-Type": "application/json; charset=utf-8",
                    // "Content-Type": "application/x-www-form-urlencoded",
                },
                redirect: "follow", // manual, *follow, error
                referrer: "no-referrer", // no-referrer, *client
                body: data, // body data type must match "Content-Type" header
            })
            .then(function(res){});
        });


    </script>
</body>
</html>

Problem here is that, it doesn't log "Hi", whereas if I delete the second parameter of fetch function and only send get request, everything works fine. What's the problem?

0

1 Answer 1

3

Your router is only set to log on a GET request, so it won't log on a POST

See here

app.get('/log', function(req, res){
    console.log("Hi");
});

app.post('/log', function(req, res){
    console.log("Hi");
});

Alternatively, you can use app.all to handle all requests.

There is a special routing method, app.all(), used to load middleware functions at a path for all HTTP request methods. For example, the following handler is executed for requests to the route “/secret” whether using GET, POST, PUT, DELETE, or any other HTTP request method supported in the http module.

app.all('/log', function (req, res, next) {
    console.log("Hi");
})

Sign up to request clarification or add additional context in comments.

3 Comments

Oh, I thought get was just a function name, now it makes sense, thank you very much, after 8 mins I will be able to approve the answer.
Also can you tell me, how can I retrieve the post parameters (the json) in app.post function?

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.