node.js - 不使用 node-fetch 调用的 Express 路由
问题描述
我有一个带有一条路线的快递服务器。当我在浏览器中调用此路由时,我能够获取服务器发送的数据。但是,当我尝试使用简单的节点获取从脚本调用此路由时,我有一个响应,但没有调用我的路由(未检索到数据)。我解释 :
这是我的快递服务器的代码:
应用程序.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);
但从未达到我的结果。
有谁知道问题出在哪里?
解决方案
我找到了为什么它不起作用。我使用了一个已经使用的随机端口(端口 9000)。更改了端口工作...
推荐阅读
- ruby-on-rails - Ubuntu - Apache:Passenger 根本没有启动 Rails 应用程序
- ansible - 在 Ansible 中,如何将标量过滤器应用于列表
- c++ - 关于重载 -> 运算符的说明
- android - 如何使用 Retrofit 2 测量巨大字符串的上传进度?
- php - 如何在 yii2 kartik 中查看图像和 pdf 文件预览 更新表单中的多个文件上传
- python - 冗余关键字参数
- java - 为其他操作系统构建 Java 模块运行时映像
- xcode - Safari 应用程序扩展未出现在 Safari 偏好设置中时如何进行故障排除?
- java - IBM Watson Assistant、Telegram 和 Python
- python - Matplotlib plt.show() 不显示任何内容