TypeError:无法获取

问题描述 投票:2回答:1

我有一个index.pug文件,由GET呈现,Post有数据返回json。

router.get('/', function(req, res, next) {
  res.render('index', { title: 'agrotaxi' });
});

router.post('/', async function(req, res) {
......
res.json(info);
});

问题是当你尝试获取我得到的结果时:

Uncaught (in promise) TypeError: Failed to fetch

我的获取功能:

   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);
       });
   }

不明白我做错了什么。 the pic of error

javascript node.js fetch
1个回答
1
投票

也许由于某种原因提取失败的问题并且您没有捕获错误,因此,尝试以这种方式添加catch方法:

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);
});
© www.soinside.com 2019 - 2024. All rights reserved.