javascript - 使用带有回调的 http.get Node.js
问题描述
我正在尝试在这里实现这个库,它会生成二维码和所有其他类型的代码。
我遇到的问题是发出一个请求,我可以访问 req 和 res 对象,因为我需要将它们传递给库。在文档中,他们推荐
http.createServer(function(req, res) {
// If the url does not begin /?bcid= then 404. Otherwise, we end up
// returning 400 on requests like favicon.ico.
if (req.url.indexOf('/?bcid=') != 0) {
res.writeHead(404, { 'Content-Type':'text/plain' });
res.end('BWIPJS: Unknown request format.', 'utf8');
} else {
bwipjs.request(req, res); // Executes asynchronously
}
}).listen(3030);
问题是我已经创建了一个服务器,我只想在获取请求中调用该库,而不创建另一个服务器。我努力了
http.get('http://localhost:3030/?bcid=azteccode&text=thisisthetext&format=full&scale=2', (req, res) => {
bwipjs.request(req, res); // Executes asynchronously
}
)
这显然不起作用,因为回调只将响应作为参数。
我想在实现中使用裸节点,因为这是我的服务器的实现方式,我不想仅为这种情况添加库(如 Express)。
解决方案
你严重误解了角色的作用http.get
http.get
用于对该特定 url进行HTTP GET调用。它基本上就是axios
or request
or ajax
or or or xhr
or postman
or做什么browser
。
的 url 参数http.get
不是路由。从字面上看,它就是您要访问的网址。
如果要处理特定路线,则必须在http.createServer()
处理程序本身中进行。
喜欢,
http.createServer(function(req, res) {
if (req.url.indexOf('/?bcid=') != 0) {
//do something
} else if (req.method == "get" && req.url.indexOf('/?bcid=') != 0){
bwipjs.request(req, res); // Executes asynchronously
} else {
//do something else
}
}).listen(3030);
查看req
或http.IncomingMessage
了解您可以使用的可用属性。
推荐阅读
- python - 将系列转换为诊断数据框,所有其他元素为零
- azure - Azure 订阅标签:如何删除空标签值?
- javascript - 将字体系列与字体名称节点 js 分开
- codenameone - 代号为一的内存数据库
- java - Java的--add-export在jlinking期间没有效果
- java - Spring Boot JacksonTester 自定义序列化程序未注册
- javascript - 比较文章和按钮的数据
- wpf - 使代码在 Sync VB.net 中执行 | WPF
- jquery - .addClass 不适用于单个 Span
- angular - 构建时出错:模块导出的意外值 null