Reputation: 49
I have a index.pug file, that is render by GET, and Post that returns data into json.
router.get('/', function(req, res, next) {
res.render('index', { title: 'agrotaxi' });
});
router.post('/', async function(req, res) {
......
res.json(info);
});
The problem is that when you try to fetch the result i've got:
Uncaught (in promise) TypeError: Failed to fetch
my fetch function:
document.getElementById('go').addEventListener('click',getdata);
function getdata() {
let start = document.getElementById('start').value;
let end = document.getElementById('end').value;
let options = {
"start": start,
"end": end
};
fetch('http://localhost:3000', {
method: 'post',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body:JSON.stringify(options)
})
.then(function(res){
return res.json(); //error here
})
.then(function(data){
console.log(data);
});
}
Don't understand what i do wrong. the pic of error
Upvotes: 3
Views: 24419
Reputation: 2799
Maybe the problem the fetch fails for some reason and you are not capturing the error, so, try adding the catch method in this way:
fetch('http://localhost:3000', {
method: 'post',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body:JSON.stringify(options)
}).then(function(res){
return res.json(); //error here
}).then(function(data){
console.log(data);
}).catch((error) => {
console.log(error);
});
Upvotes: 7