【发布时间】:2020-09-04 00:34:06
【问题描述】:
我有一个只有一条路由的快递服务器。当我在浏览器中调用此路由时,我能够获取服务器发送的数据。但是,当我尝试使用简单的节点获取从脚本调用此路由时,我有一个响应,但没有调用我的路由(未检索到数据)。我解释一下:
这里是我的快递服务器的代码:
App.ts
import express from "express";
import httpServer from "./httpServer";
import HttpRoutes from "./httpRoutes";
class BrokerServer {
public httpServer!: express.Application;
public httpRoutes!: HttpRoutes;
constructor() {
this.initHttpServer();
}
private initHttpServer(): void {
this.httpServer = httpServer;
this.httpRoutes = new HttpRoutes();
this.httpRoutes.routes();
}
}
new BrokerServer();
服务器.ts
import express from "express";
import * as bodyParser from "body-parser";
class HttpServer {
public HTTP_PORT: number = 9000;
public server!: express.Application;
constructor() {
this.server = express();
this.server.use(bodyParser.json());
this.server.listen(this.HTTP_PORT, () => {
console.log('Broker HTTP Server listening on port 9000');
});
}
}
export default new HttpServer().server;
还有我的 routes.ts
import httpServer from "./httpServer";
export default class HttpRoutes {
public routes(): void {
httpServer.get("/getNodes", (req, res) => {
console.log("GET");
res.status(200).send(JSON.stringify({ nodes: [] }));
});
}
}
当我启动我的服务器并在 URL http://localhost:9000/getNodes 上导航时,我可以看到我的 console.log('GET')。当我尝试使用 node-fetch 时,情况并非如此。
这是我的小脚本:
const fetch = require('node-fetch');
console.log('launch fetch');
fetch('http://localhost:9000/getNodes')
.then(response => {
console.log('response', response);
return response.json()
})
.then(results => {
console.log('results', results);
})
.catch(error => {
console.log('error', error);
});
通过脚本,我到达了console.log('response', response);,但没有得到我的结果。
谁知道问题出在哪里?
【问题讨论】:
标签: node.js typescript fetch node-fetch