类型错误:无法获取

Mik*_*yan 3 javascript fetch node.js

我有一个由 GET 渲染的 index.pug 文件,以及将数据返回到 json 中的 Post。

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

router.post('/', async function(req, res) {
......
res.json(info);
});
Run Code Online (Sandbox Code Playgroud)

问题是,当您尝试获取结果时,我得到了:

Uncaught (in promise) TypeError: Failed to fetch
Run Code Online (Sandbox Code Playgroud)

我的提取功能:

   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);
       });
   }
Run Code Online (Sandbox Code Playgroud)

不明白我做错了什么。 错误的图片

Jos*_*ato 6

可能是由于某种原因获取失败的问题,而您没有捕获错误,因此,尝试以这种方式添加 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);
});
Run Code Online (Sandbox Code Playgroud)

  • 补充一下,by也有同样的问题。 (2认同)