javascript 类型错误:无法获取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50556238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 09:10:22  来源:igfitidea点击:

TypeError: Failed to fetch

javascriptnode.jsfetch

提问by Mikael Nazaretyan

I have a index.pug file, that is render by GET, and Post that returns data into json.

我有一个由 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);
});

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

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

回答by Jose Mato

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:

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