Reputation: 433
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?
Upvotes: 0
Views: 644
Reputation: 1696
Your router is only set to log on a GET
request, so it won't log on a POST
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");
})
Upvotes: 3