在异步操作服务器上取消获取操作

时间:2020-03-16 06:58:56

标签: node.js express asynchronous fetch

我有一个类似的提取请求

        export class TableComponent implements OnInit {
        people: People[] = [];

        constructor(private starWarsServ: StarwarsService) { }


        ngOnInit() {
          try {
            this.starWarsServ.getByContent(`${this.route}`)
            .subscribe(data => {
              {console.log(data['results']); this.people = data['results'].name;}
            })


          catch(err) {
            throw err;
          }
          }

还有一个nodejs表达请求的快速路由器(express-promise-router)

fetch(`http://localhost:4000/test`, {
  method: 'GET',
  mode: 'cors',
  cache: 'no-cache',
  headers: {
    'Content-Type': 'application/json'
  }
})
.then(result => console.log('success'))
.catch(error => console.log('error', error));

调用fetch时记录成功。这样很好。 但是,当我将nodejs路由器功能更改为类似

this.router.get('/test', (request: Request, response: Response) => {
  response.status(200).send({'status': 'ok'});
});

获取操作被取消,控制台日志显示this.router.get('/test', (request: Request, response: Response) => { return asyncFunction().then(result => response.status(200).send({'status': 'ok'})); });

当我使用浏览器URL或Postman调用/ test api时,获得了成功的结果。 我不知道为什么提取失败。 (也曾在Axios上尝试过,但结果相同。)

1 个答案:

答案 0 :(得分:0)

我在提取问题上走错了路。 问题与提取无关,而与调用提取的事件有关。 在方法的最后,我需要一个event.preventDefault(),以便事件被停止并且提取得到正确处理。