Ошибка типа: не удалось получить - PullRequest
0 голосов
/ 27 мая 2018

У меня есть файл 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);
       });
   }

Не понимаю, что я делаю неправильно. рис ошибки

1 Ответ

0 голосов
/ 27 мая 2018

Возможно, проблема в том, что выборка не удалась по какой-то причине, и вы не фиксируете ошибку, поэтому попробуйте добавить метод 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);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...